在多维数组PHP中搜索重复项

时间:2013-02-10 13:24:41

标签: php arrays multidimensional-array

我在JSON中有一个多维PHP数组:

array = [{
          "id":"1",
          "key":"Ferrari",
          "type":"car"},
         {
          "id":"1",
          "key":"Red",
          "type":"color"},
         {
          "id":"73",
          "key":"Yellow",
          "type":"color"
         }]

因为它实际上是一个搜索结果,我想动态组合id相同的结果。换句话说,新数组应如下所示:

    array = [{
          "id":"1",
          "key":"Red Ferrari",
          "type":"keyword"}, 
         {
          "id":"73",
          "key":"Yellow",
          "type":"color"
         }]

我一直在研究很多PHP函数,但它们在多维数组中的功能有限。任何建议都赞赏:)

很多问候 安德烈亚斯

1 个答案:

答案 0 :(得分:1)

没有基本功能可以像你提到的那样具体。所以你可以做这样的事情:

print_r(my_array_merge($data));
function my_array_merge($data)
{
    // sort all records by id to merge them later
    $data_by_id = array();
    foreach ($data as $item)
    {
        if (!isset($data_by_id[ $item['id'] ])) {
            $data_by_id[ $item['id'] ] = array();
        }
        $data_by_id[ $item['id'] ][] = $item;
    }
    // merge records with same id
    $return = array();
    foreach ($data_by_id as $id => $items)
    {
        foreach ($items as $item)
        {
            if (!isset($return[ $id ])) {
                $return[ $id ] = $item;
            } else {
                $return[ $id ]['key'] .= ' ' . $item['key'];
                $return[ $id ]['type'] = 'keyword'; // I don't really get what you mean by 'keyword'
            }
        }
    }
    // reset keys before return
    return array_values($return);
}