0

所以我正在尝试编写一个方法,将所有数组与某个键值合并,但我遇到的问题是,当我尝试取消设置数组时,不会出现重复的结果,它会跳过几个事情,这让我很困惑。所以任何关于我如何改进这种方法的建议都将不胜感激。我的另一个问题..有没有办法检查这些数组中的每一个是否都有我正在寻找的所有 4 个键。

'发布日期' => '电子表格和传单月份' => '每月更新中的广告' => '目录中的功能' =>

所以我正在做的是在数据库中合并具有相同 id 的数组,所以我不必做一些非常讨厌的 SQL 查询,但我想知道是否有一种方法可以确保所有 4 个键将在每个结果中......如果有一个与一个或多个相关联的值......我的方法会将值添加到它的键中,如果没有与键关联的值,它只会生成一个空字符串。

protected function array_with_same_val($array, $key) {

    for($i = 0; $i < count($array); $i++) {
        for($j = 1; $j < count($array); $j++) {
            if(isset($array[$j]) && isset($array[$i]) && $array[$i][$key]==$array[$j][$key]) {
                $temp = array_merge($array[$i], $array[$j]);
                $array[$i] = $temp; 
                //unset($array[$j]);    
            } 
        }
    }   

    return $array;
}

这是我的数组的一个示例(会有更多的值,这只是为了提供一个想法):

    '0' => array
    (
        'Release Date' => 'September 1, 2013',
        'cp_id' => '112960' 
    ),

    '1' => array
    (
         'Spreadsheet and Flyer Month' => 'September 1, 2013',
         'cp_id' => '112960' 
    ),

    '2' => array
    (
         'Advertise in Monthly Update' => 'September 1, 2013',
         'cp_id' => '112960' 
    ),

    '3' => array
    (
       'Release Date' => 'September 1, 2013',
         'cp_id' =>  '109141' 
    ),
    );

对此的任何帮助将不胜感激。

4

1 回答 1

1

试试这个($input 是您在上面提供的数组)...

$output = array();
$requiredKeys = array('Release Date' => '', 'Spreadsheet and Flyer Month' => '', 'Advertise in Monthly Update' => '', 'Feature in Catalog' => '');

foreach ($input as $item) {
    if (array_key_exists($item['cp_id'], $output)) {
        $output[$item['cp_id']] = array_merge($output[$item['cp_id']], $item);
    } else {
        $output[$item['cp_id']] = array_merge($requiredKeys, $item);
    }
}

$output = array_values($output);

底部的 array_values 调用只是从数组中删除字符串键。

于 2013-03-11T19:27:56.780 回答