Find all items with the same key in array and combine them in a new one

北慕城南 提交于 2019-12-13 10:30:10

问题


Let's suppose we have a multidimensional array like below:

$obj = array
(
array("carName"=>"Volvo","carColor"=>"Red", "carSpeed"=> "100 mph"),
array("carName"=>"Volvo","carColor"=>"Blue", "carSpeed"=> "100 mph"),
array("carName"=>"BMW","carColor"=>"White", "carSpeed"=> "120 mph"),
array("carName"=>"BMW","carColor"=>"Grey", "carSpeed"=> "120 mph")
);

How can I combine the "carColor" of every "carName" in a single array so that I get:

$newObj = array
(
array("carName"=>"Volvo","carColor"=> array("Red", "Blue"), "carSpeed"=> "100 mph"),
array("carName"=>"BMW","carColor"=> array("White", "Grey"), "carSpeed"=> "120 mph")
);

回答1:


If you name each array with the car name (not sure if that matters) you can do it this way

foreach($obj as $x=>$y){
$new[$y['carName']]['carName']=$y['carName'];
$new[$y['carName']]['carColor'][]=$y['carColor'];
$new[$y['carName']]['carSpeed']=$y['carSpeed'];
}


来源:https://stackoverflow.com/questions/46775864/find-all-items-with-the-same-key-in-array-and-combine-them-in-a-new-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!