gpt4 book ai didi

php - 从 json 中检索键和值

转载 作者:搜寻专家 更新时间:2023-10-31 21:25:14 25 4
gpt4 key购买 nike

我有这个 JSON 字符串:

$json= '{"data":[{"id":"123","name":"john smith","gender":"MALE","phone":[{"number":"+919999999999","numberType":"MOBILE"}]}]}'

我想从 json 中检索所有的值和键,输出应该如下所示:

id:         123
name: john smith
gender: MALE
phone:
number: +919999999999
numberType: MOBILE

我试过这段代码,但它无法获得电话输出:

$jsond = json_decode($json);
foreach($jsond->data as $row)
{
foreach($row as $key => $val)
{
echo $key . ': ' . $val;
}
}

最佳答案

这正是array_walk_recursive用于:

<?php

$json = '{"data":[{"id":"123","name":"john smith","gender":"MALE","phone":[{"number":"+919999999999","numberType":"MOBILE"}]}]}';

$jsond = json_decode($json,true);

function test_print($val, $key)
{
echo "$key : $val<br/>\n";
}

array_walk_recursive($jsond, 'test_print');

导致此输出:

id : 123<br/>
name : john smith<br/>
gender : MALE<br/>
number : +919999999999<br/>
numberType : MOBILE<br/>

关于php - 从 json 中检索键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37623845/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com