使用php

时间:2016-08-26 21:40:43

标签: php arrays multidimensional-array associative-array

我有两个阵列。

$all_labels = [
    'data'=> [
        ['label'=> NULL],
        ['label'=> "C1.SNM"],
        ['label'=> "C1.SSM"],
        ['label'=> "C1.TAM"],
        ['label'=> "C1.TIM"],
        ['label'=> "C1.TNM"],
        ['label'=> "C1.TOM"]
    ]
];

$non_complianceData3 = [
    'data'=> [
        ['label'=> "C1.TAM", 'value'=> "1674"],
        ['label'=> "C1.TOM", 'value'=> "574"]
    ]
];

我需要第一个数组作为基础,即返回db中可用的所有标签。然后,我需要使用带有匹配标签的$non_complianceData3数组数据值来更新基数,在这种情况下,需要使用"C1.TAM"和{{1}更新基数'value'=> "1674""C1.TOM"

我该怎么做?

1 个答案:

答案 0 :(得分:0)

如果$all_labels中的标签不同,可以这样做:

// reindex $all_labels['data'] by label
$all_labels['data'] = array_column($all_labels['data'], null, 'label');

// assign the values from $non_complianceData3['data'] to the new keys
foreach ($non_complianceData3['data'] as $item) {
    $all_labels['data'][$item['label']] = $item;
}

如果$all_labels中的标签不明显,可以这样做:

// loop over the items in $non_complianceData3['data']
foreach ($non_complianceData3['data'] as $item) {

    // find all of the matching labels in $all_labels['data'] and replace
    // them with the corresponding $non_complianceData3['data'] items
    foreach ($all_labels['data'] as $key => $value) {
        if ($item['label'] == $value['label']) {
            $all_labels['data'][$key] = $item;
        }
    }
}