如何循环遍历多层数组并替换其中的某些关联值?
例如,这是我的数组,
$items = array(
0 => array(
"id" => "1",
"title" => "parent 1",
"children" => array()
),
1 => array(
"id" => "2",
"title" => "parent 2",
"children" => array (
0 => array(
"id" => "4",
"title" => "children 1",
"granchildren" => array(
0 => array(
"id" => "7",
"title" => "granchildren 1"
),
1 => array(
"id" => "8",
"title" => "granchildren 2"
)
)
),
1 => array(
"id" => "5",
"title" => "children 2",
"granchildren" => array()
)
),
),
3 => array(
"id" => "3",
"title" => "parent 3",
"children" => array()
)
);
这是我的两个功能,
function translate ($id){
$items = array(
0 => array(
"id" => 1,
"title" => "parent 1 en"
),
1 => array(
"id" => 4,
"title" => "children 1 en"
),
2 => array(
"id" => 8,
"title" => "granchildren 2 en"
)
);
foreach($items as $item) {
if($id === $item['id'])
{
return $item['title'];
}
}
}
function looper ($items){
$new_items = array();
foreach($items as $key => $item) {
if(isset($key) && is_array($key)){
$new_items[$key] = translate($item['id']);
}else {
//looper($item);
}
}
return $new_items;
}
print_r(looper ($items));
这是我追求的结果,
Array
(
[0] => Array
(
[id] => 1
[title] => parent 1 en // translated
[children] => Array
(
)
)
[1] => Array
(
[id] => 2
[title] => parent 2
[children] => Array
(
[0] => Array
(
[id] => 4
[title] => children 1 en // translated
[granchildren] => Array
(
[0] => Array
(
[id] => 7
[title] => granchildren 1
)
[1] => Array
(
[id] => 8
[title] => granchildren 2 en // translated
)
)
)
[1] => Array
(
[id] => 5
[title] => children 2
[granchildren] => Array
(
)
)
)
)
[3] => Array
(
[id] => 3
[title] => parent 3
[children] => Array
(
)
)
)
有可能吗?
答案 0 :(得分:1)
听起来像是array_walk
或array_walk_recursive
的工作
它将为数组中的每个项调用用户提供的函数。您可以通过引用修改数组,以实现您的目标。