猿问

获取json响应php的元素名称和值

我想从 json 响应中获取所有元素及其值。我有以下回复(片段,它有更多元素):


stdClass Object ( [Count] => 15244 [Warnings] => Array ( ) [Machines] => Array ( [0] => stdClass Object ( [Id] => 23 [Modified] => 2019-09-18 06:38:04 [Created] => 2016-03-10 14:11:39 ) [1] => stdClass Object ( [Id] => 51 [Modified] => 2019-09-18 08:15:52 [Created] => 2016-06-15 09:13:16 )))

现在我想得到类似的结果:


ID: 23, Modified: 2019-09-18 06:38:04, Created: 2016-03-10 14:11:39

ID: 51, Modified: 2019-09-18 08:15:52, Created: 2016-06-15 09:13:16

问题是,我不想硬编码元素名称,如“ID”、“Created”等,因为每台机器的完整数组大约有 50 个元素。


这是我尝试过的:


$obj = json_decode($body);


foreach ($obj->Machines as $comp) {

    $sup =key($comp);

    echo key($comp)."-".$comp->$sup."<br>";

}

但这只会给出输出:


Id-23

Id-51

所以我只得到第一个 KEY 显示。我不知道如何在循环中找到下一个元素,如“修改”。


感谢您的支持!


喵喵时光机
浏览 160回答 3
3回答

暮色呼如

您可以使用数组映射来回显相同的内容,foreach ($obj->Machines as $comp) {&nbsp; &nbsp; echo implode(', ', array_map(function ($val, $key) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return sprintf("%s:'%s'", $key, $val);&nbsp; &nbsp; &nbsp; &nbsp; }, $comp, array_keys($comp)))."<br/>";}解决方案2: -foreach ($obj->Machines as $comp) {&nbsp; &nbsp; echo str_replace('=',':',http_build_query($comp,'',', '));}http_build_query — 生成 URL 编码的查询字符串

慕码人2483693

使用 . 将您的 JSON 数据转换为数组json_decode()。使用array_map()对数组进行迭代,再次使用array_walk()进行另一个嵌套迭代以将值替换为key:value梨格式。最后通过逗号的胶水将转换后的数组连接到字符串。代码示例:$response = json_decode($response, true);$result = array_map(function ($val) {&nbsp; &nbsp; array_walk($val, function (&$v, $k) { $v = "$v: $k"; });&nbsp; &nbsp; return implode(',', $val);}, $response);print_r($result);

qq_遁去的一_1

您所做的是正确的,尽管这是一个多维数组。您需要几个 foreach 循环来迭代到您想要的维度。$response = [];foreach($obj->Machines as $comp) {&nbsp; &nbsp; foreach($comp as $key => $value) {&nbsp; &nbsp; &nbsp; &nbsp; $response[$key] = '';&nbsp; &nbsp; &nbsp; &nbsp; foreach($value as $title => $display) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $response[$key] .= $title . ': ' . $display . ', ';&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; $response[$key] = rtrim($response[$key], ', ');&nbsp; &nbsp; }}&nbsp; &nbsp;var_dump($response);
随时随地看视频慕课网APP
我要回答