遍历多个数组并执行函数 [英] Iterate through multiple array and execute function
本文介绍了遍历多个数组并执行函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个具有以下结构的数组:
I have an array with the following structure:
Array
(
[0] => Array
(
[animal] => dog
[color] => black
)
[1] => Array
(
[animal] => cat
[color] => white
)
[2] => Array
(
[animal] => mouse
[color] => grey
[attributes] => Array
(
[nickname] => snuggles
[nickname] => buddy
)
)
)
我现在需要对属性数组中的每个值执行一个函数。因此,例如将 SNUGGLES
和 BUDDY
大写。
I now need to execute a function on every value in the attribute array. So for example capitalize SNUGGLES
and BUDDY
.
此是我的方法:
$array = array(
array("animal"=>"dog","color"=>"black"),
array("animal"=>"cat","color"=>"white"),
array("animal"=>"mouse","color"=>"grey", "attributes" => array("nicknames" => "snuggles", "nicknames" => "buddy"))
);
foreach ( $array as $key => $value ) {
foreach ( $value as $key1 => $value1 ) {
if ($key1 == 'attributes') {
foreach ( $value as $key2 => $value2 ) {
$value2 = strtoupper($value2);
$array [$key] [$key1] [$key2]= $key2;
}
}
}
}
但是我收到此错误:
strtoupper()期望参数1为字符串,并在...
strtoupper() expects parameter 1 to be string, array given in ...
推荐答案
您在内部循环中使用了错误的变量:
You are using the wrong variable in your inner loop:
foreach ( $value as $key2 => $value2 ) {
^^^^^^ here
...
}
根据代码判断,您想使用 $ value1
那里:
Judging by the code, you would want to use $value1
there:
foreach ( $value1 as $key2 => $value2 ) {
^^^^^^^ here
...
}
假设下拉列表
=> 属性
...
Assuming that dropdown
=> attributes
...
这篇关于遍历多个数组并执行函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文