I have an array like
Array
(
[0] => Array
(
[id] => 24
[resource_id] => 34
)
[1] => Array
(
[id] => 24
[resource_id] => 1
)
[2] => Array
(
[id] => 25
[resource_id] => 2
)
[3] => Array
(
[id] => 25
[resource_id] => 34
)
)
I want to merge these arrays using 'id' and output should be like
Array
(
[0] => Array
(
[id] => 24
[resource_id] => 34,1
)
[1] => Array
(
[id] => 25
[resource_id] => 2,34
)
)
Also want to merge resource_id
separated with commas.
Try it , this do your question (Ever the first array sorted by id):
<?php
$arrayToMerge = array(0=>array("id"=>24,"resource_id"=>34) , 1=>array("id"=>24,"resource_id"=>1) , 2=>array("id"=>25,"resource_id"=>2) , 3=>array("id"=>25,"resource_id"=>34));
$tmpArray;
$lastID = "";
$ids = "";
$count = 0;
foreach ($arrayToMerge as $key => $value) {
$lastID = $value['id'];
if (empty($ids)) {
$ids = $lastID;
$tmpArray = array();
array_push($tmpArray,array("id"=>$ids,"resource_id"=>$value['resource_id']));
} else if (strcmp($lastID,$ids)==0){
$tmpValue = $tmpArray[$count]['resource_id'];
$tmpArray[$count]['resource_id'] = $tmpValue.','.$value['resource_id'];
} else {
$ids = $lastID;
array_push($tmpArray,array("id"=>$ids,"resource_id"=>$value['resource_id']));
$count++;
}
}
var_dump($tmpArray);
?>
I think this would help you to make what you need
<?php
$myArray = [
["id"=>1,"value"=>10],
["id"=>1,"value"=>20],
["id"=>1,"value"=>30],
["id"=>2,"value"=>40],
["id"=>2,"value"=>50]
];
$sumArray = array();
foreach ($myArray as $k=>$value) {
$sumArray[$value['id']] .= ($sumArray[$value['id']]) ? ", ":"";
$sumArray[$value['id']] .= $value['value'];
}
print_r($sumArray);
?>
Play here : https://eval.in/694544
Check here if you tried and still not solved your problem : https://eval.in/694562