首先让我说,我已经通过了很多相关的问题在这里,但没有一个解决我的问题。我有和php嵌套数组在db和需要打印所有的值。输出输出第一个最顶层数组(它是'name',值为"Office, home"),但没有得到'BB"中包含的嵌套数组值。这是我的代码:
function getTB($name='', $value='') {
$value = json_decode($value);
$name = ''; $BB= '';
foreach ($value as $key=>$val) {
$name .= $val['name'].',';
JSON代码:[{"name":"Office","TB":[{"date":[false,true],"time":"8:00 AM"}]},{{"days":[false,true],"time":"6:00 PM"},
use array_walk_recursive
如果你有这样的json(它有一个子数组)
$decoded = json_decode('{"abc": "one",
"def": "two",
"sub_array": {
"ABC": "ONE"
}}', true);
array_walk_recursive($decoded, function($value,$key) {
echo $key.' :'.$value.'<br>';
});
输出将是
abc :one
def :two
ABC :ONE
所以像这样使用而不是普通的foreach
更新
像这样使用
$arr='[{"name":"Office","TB":[{"date":[false,true],"time":"8:00 AM"},{"days":[false,true],"time":"6:00 PM"}]}]';
$rr=json_decode($arr);
foreach ($rr[0]->TB as $key => $value) {
array_walk_recursive($value, function($k,$kk){
echo 'Key is '.$kk.' & Value is '.$k.'<br>';
});
}
输出:
Key is 0 & Value is
Key is 1 & Value is 1
Key is time & Value is 8:00 AM
Key is 0 & Value is
Key is 1 & Value is 1
Key is time & Value is 6:00 PM