我正在尝试遍历一个多维数组,并添加一个新的子数组。我的代码没有返回任何错误,但也没有添加新项目。
我有以下代码:
foreach ($data['switches'] as $switch) {
foreach ($switch['atags'] as $attributelist) {
$nohardwareAttribFound = false;
foreach ($attributelist as $attribute) {
$pos = strpos(trim($attribute),'$attr_2_');
if ($pos !==false) {
//echo 'in the loop';
//found it. extract and exit loop
$modelnumber = substr(trim($attribute),8);
$hardwaremodel = array();
$hardwaremodel['tag'] = 'hardware_model:'.$modelnumber;
array_push($switch['atags'],$hardwaremodel);
print_r($switch);
//echo '<br>=====<br>';
$nohardwareAttribFound = true;
}
}//end foreach ($attributelist
}// end foreach ($switch['atags']
if ($nohardwareAttribFound==false) {
$hardwaremodel['tag'] = 'Unknown';
array_push($switch['atags'],$hardwaremodel);
}//end if
}// end foreach ($data['switches']
我希望数据看起来像:
[atags] => Array (
[0] => Array ( [tag] => $id_365 )
[1] => Array ( [tag] => $typeid_8 )
[2] => Array ( [tag] => $any_object )
[3] => Array ( [tag] => $casd )
[4] => Array ( [tag] => $unmounted )
[5] => Array ( [tag] => $no_asset_tag )
[6] => Array ( [tag] => $attr_2_1086 )
[7] => Array ( [tag] => $untagged )
[8] => Array ( [tag] => hardware_model:1086 ) ) )
其中最后一个数组 - element[8]
代表我添加的一个新子数组。该print_r()
语句看起来是正确的,但是当我遍历传递给我的视图的结果时,我可以看到实际上并没有添加一个新的标签数组。
我需要某种替换而不是替换array_push()
吗?
如果在循环遍历数组时修改数组不是一个好主意,我可以简单地检查一个项目是否存在。我将如何检查每个开关的 ['atags'] 数组是否包含一个 [tag],其值看起来像“$attr_2_NNNN”,其中 N 是一个数字?例如,检查上面示例数组中的元素 6。挑战在于它并不总是元素 6,并且您并不总是保证标签将具有 attr_2 值。我知道有一个in_array()
功能......我会尝试类似的东西:
if (in_array(array('$attr_2_'), $switches['atags']))
我对 $nohardwareAttribFound 变量的逻辑有一个错误,我将对其进行修复。
谢谢