下面我有2个PHP数组。 $all_tags
和$list_tags
我需要迭代$all_tags
数组,并为'class' => 'added'
中的每个数组项添加一个键/值$all_tags
,该数组项具有匹配的数组项$list_tags
$all_tags
1}}数组。
在下面的示例数据中,id
数组中class
值为1,2和5的项目将具有名为added
的值,其值为{ {1}}。
$all_tags = array();
$all_tags[] = array(
'id' => 1,
'title' => 'title 1',
'description' => 'description 1'
);
$all_tags[] = array(
'id' => 2,
'title' => 'title 2',
'description' => 'description 2'
);
$all_tags[] = array(
'id' => 3,
'title' => 'title 3',
'description' => 'description 3'
);
$all_tags[] = array(
'id' => 4,
'title' => 'title 4',
'description' => 'description 4'
);
$all_tags[] = array(
'id' => 5,
'title' => 'title 5',
'description' => 'description 5'
);
$list_tags = array();
$list_tags[] = array(
'id' => 1,
'title' => 'title 1',
'description' => 'description 1'
);
$list_tags[] = array(
'id' => 2,
'title' => 'title 2',
'description' => 'description 2'
);
$list_tags[] = array(
'id' => 5,
'title' => 'title 5',
'description' => 'description 5'
);
foreach($all_tags as $key => $val){
echo $val;
}
答案 0 :(得分:2)
在您的简单情况下,使用带foreach
函数的常规in_array
循环就足够了:
...
foreach ($all_tags as &$v) {
if (in_array($v, $list_tags)) {
$v['class'] = 'added';
}
}
print_r($all_tags);
输出:
Array
(
[0] => Array
(
[id] => 1
[title] => title 1
[description] => description 1
[class] => added
)
[1] => Array
(
[id] => 2
[title] => title 2
[description] => description 2
[class] => added
)
[2] => Array
(
[id] => 3
[title] => title 3
[description] => description 3
)
[3] => Array
(
[id] => 4
[title] => title 4
[description] => description 4
)
[4] => Array
(
[id] => 5
[title] => title 5
[description] => description 5
[class] => added
)
)
答案 1 :(得分:1)
我的建议是首先获取$list_tags
ID,然后仅在$all_tags
上进行迭代。
当数组不完全相同但id
匹配时,此方法将起作用。
$list_tags_ids = array_column($list_tags, 'id');
foreach($all_tags as &$val){
if(in_array($val['id'], $list_tags_ids)) {
$val['class'] = 'added';
}
}
答案 2 :(得分:-1)
我有这个方法来做所需的输出。我也总是对其他方式开放=)
$all_tags = array();
$all_tags[] = array(
'id' => 1,
'title' => 'title 1',
'description' => 'description 1'
);
$all_tags[] = array(
'id' => 2,
'title' => 'title 2',
'description' => 'description 2'
);
$all_tags[] = array(
'id' => 3,
'title' => 'title 3',
'description' => 'description 3'
);
$all_tags[] = array(
'id' => 4,
'title' => 'title 4',
'description' => 'description 4'
);
$all_tags[] = array(
'id' => 5,
'title' => 'title 5',
'description' => 'description 5'
);
$list_tags = array();
$list_tags[] = array(
'id' => 1,
'title' => 'title 1',
'description' => 'description 1'
);
$list_tags[] = array(
'id' => 2,
'title' => 'title 2',
'description' => 'description 2'
);
$list_tags[] = array(
'id' => 5,
'title' => 'title 5',
'description' => 'description 5'
);
foreach ($all_tags as $allTagKey => $allTagElement) {
foreach ($list_tags as $listTagKey => $listTagElement) {
if ($allTagElement['id'] == $listTagElement['id']) {
$all_tags[$allTagKey]['class'] = 'added';
break; // for performance and no extra looping
}
}
}
echo '<pre>';
print_r($all_tags);