我在PHP中有一个多维数组,显示为:
Array
(
[0] => Array
(
[background] => https://example.com/image.jpg
[description] => Example text
[url] => https://example.com
)
[1] => Array
(
[background] => https://example.com/image.jpg
[description] => Example text
[url] => https://example.com
)
)
我想遍历此数组并将相同的参数附加到url
个键。我尝试通过带有双foreach循环的函数执行此操作,并且能够成功附加参数,但是我无法返回具有更新值的数组。
这是我尝试过的:
拨打
$array = append_field($array, 'url', '?parameter=test');
功能
function append_field($array, $field, $parameter)
{
foreach ($array as $inner_array) :
foreach ($inner_array as $key => $append) :
if ($key == $field) :
$append .= $parameter;
endif;
endforeach;
endforeach;
return $array;
}
答案 0 :(得分:3)
您需要在两个foreach循环中将数组值作为引用传递,以便能够写入它们。否则,您将迭代您的值的副本。
参考:http://php.net/manual/en/language.references.php
function append_field($array, $field, $parameter)
{
foreach ($array as &$inner_array) :
foreach ($inner_array as $key => &$append) :
if ($key == $field) :
$append .= $parameter;
endif;
endforeach;
endforeach;
return $array;
}
但是你也可以在没有引用的情况下完成它,这次是通过写入包括两个键的完整数组路径:
function append_field($array, $field, $parameter)
{
foreach ($array as $i => $inner_array) :
foreach ($inner_array as $key => $append) :
if ($key == $field) :
$array[$i][$key] .= $parameter;
endif;
endforeach;
endforeach;
return $array;
}
答案 1 :(得分:3)
只需更改此行
即可$append .= $parameter;
到这个
$inner_array[$key] = $append.$parameter
和foreach ($array as $inner_array):
到foreach ($array as &$inner_array) :
答案 2 :(得分:2)
更多方法,以获得相同的结果,例如使用array_map()
[akshay@localhost tmp]$ cat test.php
<?php
$arr = array(
array(
'background'=>'https://example.com/image.jpg',
'description'=>'Example text',
'url'=>'https://example.com'
),
array(
'background'=>'https://example.com/image.jpg',
'description'=>'Example text',
'url'=>'https://example.com'
),
);
$append = array('url'=>'?parameter=test');
print_r(
array_map(function($item) use ($append) {foreach($append as $k => $v){ if(isset($item[$k]))$item[$k].=$v;}return $item;}, $arr )
);
?>
输出:
[akshay@localhost tmp]$ php test.php
Array
(
[0] => Array
(
[background] => https://example.com/image.jpg
[description] => Example text
[url] => https://example.com?parameter=test
)
[1] => Array
(
[background] => https://example.com/image.jpg
[description] => Example text
[url] => https://example.com?parameter=test
)
)