使用密钥合并数组

时间:2014-01-30 10:48:11

标签: php arrays

我有php阵列

Array
(
    [0] => stdClass Object
        (
            [id] => 9956
            [event_url_node_id] => 2722
            [tree_id] => 2
            [node] => 2620
        )

    [1] => stdClass Object
        (
            [id] => 9957
            [event_url_node_id] => 2722
            [tree_id] => 2
            [node] => 4
        )

    [2] => stdClass Object
        (
            [id] => 9958
            [event_url_node_id] => 2722
            [tree_id] => 2
            [node] => 2619
        )

    [3] => stdClass Object
        (
            [id] => 9959
            [event_url_node_id] => 2722
            [tree_id] => 1
            [node] => 5746
        )

    [4] => stdClass Object
        (
            [id] => 9960
            [event_url_node_id] => 2722
            [tree_id] => 1
            [node] => 5952
        )

)

现在我想检查合并数组键tree_id
像所有tree_id == 2那样它出来array("tree_id"=>2,"node"=>2620,4,2619);
如果tree_id == 1那么它出来array("tree_id"=>1,"node"=>5746,5952)
有什么建议吗? 感谢

1 个答案:

答案 0 :(得分:1)

试试这个:

$finalArray = array();
foreach($array as $val) {
  if(array_key_exists($val->tree_id, $finalArray)) {
   $finalArray[$val->tree_id]['node'] .= ','.$val->node;
  } else {
   $finalArray[$val->tree_id]['node'] = $val->node; 
  } 
  $finalArray[$val->tree_id]['tree_id'] = $val->tree_id;
}

$finalArray将拥有您希望的元素,此数组将由tree_id索引