假设我有一个像:
这样的数组$thing = Array ( [test1] => something [test2] => something [info] => yes [array] => Array ( [test1] => something else [test2] => something else [info] => maybe [array] => Array ( [test1] => something [info] => yes ) ) )
如果'info'的值为'yes'并且{{}>我如何编写一个经过$thing
的函数,并为名为'valid'的每个部分添加一个键,其值为TRUE
{1}}否则?
我基本上希望最终数组看起来像:
$final = Array ( [test1] => something [test2] => something [info] => yes [valid] => TRUE //add this [array] => Array ( [test1] => something else [test2] => something else [info] => maybe [valid] => FALSE //add this [array] => Array ( [test1] => something [info] => yes [valid] => TRUE //add this ) ) )
我正在编写一个用于管理站点地图的codeigniter库,并提供了获取页面的面包屑和导航树的简单方法,但我遇到了需要做这样的事情的部分。
我无法弄清楚的主要问题是: 如何浏览阵列并为每个部分添加密钥?数组中也可以有无限数量的数组。
谢谢!
答案 0 :(得分:2)
这感觉就像你在添加冗余信息一样。你为什么不能重新使用数组中的数据 - 即
[info] => yes
答案 1 :(得分:2)
function setInfoTrueFalse($array){
if(isset($array['info']) && $array['info']=='yes'){
$array['valid']=TRUE;
}else{
$array['valid']=FALSE;
}
foreach($array as $key => $val){ # if we don't know the name of possible arrays, loop though
if(is_array($val)){
# loop one layer deeper if we have another array, could combine with the 'info' check if yes to that means this array exists and is an array
$array[$key]=setInfoTrueFalse($array[$key]);
}
}
return $array;
}
$final=setInfoTrueFalse($thing);
答案 2 :(得分:1)
您可以使用此
$thing = Array
(
"test1" => "something",
"test2" => "something",
"info" => "yes",
"array" => Array
(
"test1" => "something else",
"test2" => "something else",
"info" => "maybe",
"array" => Array
(
"test1" => "something",
"info" => "yes"
)
)
);
function validPush($array)
{
foreach ($array as $key => $value)
{
if(is_array($value))
$array[$key] = validPush($value);
if($key == "info")
$array['valid'] = ($value == "yes") ? true : false ;
}
return $array;
}
var_dump(validPush($thing));
输出
array
'test1' => string 'something' (length=9)
'test2' => string 'something' (length=9)
'info' => string 'yes' (length=3)
'array' =>
array
'test1' => string 'something else' (length=14)
'test2' => string 'something else' (length=14)
'info' => string 'maybe' (length=5)
'array' =>
array
'test1' => string 'something' (length=9)
'info' => string 'yes' (length=3)
'valid' => boolean true
'valid' => boolean false
'valid' => boolean true
答案 3 :(得分:0)
为什么不将jus添加到第一个数组并认为它对其余数组有效。
编辑:做一个递归调用,传递$ array,具体取决于你得到多少维数组,这里3。
function add_array( $array) {
$array['info'] = 'yes';
return $arr;
}
致电:
$final = add_array(add_array(add_array($final)));