php - How do I compare object values that are inside an array? -
i have array containing several objects.
$products = [ {"id":"1","random":"sadasd","mergethis":"ding"}, {"id":"2","random":"assdfsadf","mergethis":"ding"}, {"id":"2","random":"assdfsadf","mergethis":"flop"}, {"id":"2","random":"assdfsadf","mergethis":"bips"}, {"id":"3","random":"sdfss","mergethis":"flung"}, {"id":"3","random":"sdfss","mergethis":"rorg"}, {"id":"4","random":"asdasdddaf","mergethis":"shwung"} ]
i'm trying iterate trough array , when id
allready present in array, want add value of mergethis
first hit has same id
, seperated comma, , unset object array.
so expected outcome become:
[ {"id":"1","random":"sadasd","mergethis":"ding"}, {"id":"2","random":"assdfsadf","mergethis":"ding,flop,bips"}, {"id":"3","random":"sdfss","mergethis":"flung,rorg"}, {"id":"4","random":"asdasdddaf","mergethis":"shwung"} ]
i'm trying iterate trough $products
, compare values i'm stuck @ comparing value subvalue of array in stead of entire array
foreach($products $key => $value){ if (in_array($value->id, $products)) { //delete item , add product_category comma sepereated first item //unset($products[$key]); } }
this doesn't work because compares item entire array in stead of sub value id
of array item.
how go getting expected outcome?
do need create new array filled keys , id
values of each array item , iterate trough that? or there easier method compare object values inside array each other?
hint: use associative array id
key , whole product value:
$results = array(); foreach ($products $prod){ if (array_key_exists($prod['id'], $results)){ $results[$prod['id']]['mergethis'] .= ',' . $prod['mergethis']; } else { $results[$prod['id']] = $prod; } }
Comments
Post a Comment