1

我在 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 函数,但它们在多维数组中的功能有限。任何建议表示赞赏:)

许多问候
安德烈亚斯

4

1 回答 1

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);
}
于 2013-02-10T13:36:20.230 回答