【问题标题】:How to echo json_decode array?如何回显 json_decode 数组?
【发布时间】:2021-09-14 04:35:19
【问题描述】:

我已从服务器获取 json 数据并使用 json_decode(value, true); 进行解码

使用 print_r 函数我得到这个数组作为输出

Array
(
    [id] => 120
    [key] => 7ca04960a36dbb7f4b7c8607bb3
    [num] => 0
)

Array
(
    [id] => 121
    [key] => 7ca04960a36dccgki49g6dfg57
    [num] => 0
)

我想使用 while 循环显示解码数据。

while($row = mysqli_fetch_assoc($result)) {
    $json = json_decode($row['post_req'], true);

    echo "<pre>";
    print_r($json);
    echo "</pre>";
}

例如:

id = 120,
key = 7ca04960a36dbb7f4b7c8607bb3,
num = 0

如何打印数据?

【问题讨论】:

  • edit您的问题并发布您正在使用的whileloop。你有任何错误吗?没有输出?错误的价值观?您是否尝试过使用foreach
  • @brombeer 我已经编辑了问题

标签: php arrays json arraylist echo


【解决方案1】:

已编辑:您似乎更改了一些细节。

看起来你得到了多个数组

$output = array();

while($row = mysqli_fetch_assoc($result)) {
    $json = json_decode($row['post_req'], true);
    $ouput[] = $json;
}

这将为您提供一个多层数组,如果您只想要 id,您可以这样做

for ($i = 0; $i < sizeof($output); $i++) {
    echo "id =" . $output[$i]['id'] . " <br/>";
}

或者你可以用它来只获取id

for ($i = 0; $i < sizeof($output); $i++) {
    foreach ( $output[$i] as $key => $value ) {
      if ('id' === $key) {
        echo "$key = $value <br />";
      }
    }
}

预期的输出是

id = 120
id = 121

如果你想要所有三个值都使用这个

for ($i = 0; $i < sizeof($output); $i++) {
    foreach ( $output[$i] as $key => $value ) {
      echo "$key = $value <br />";
    }
}

预期输出

id = 120
key = 7ca04960a36dbb7f4b7c8607bb3
num = 0
id = 121
key = 7ca04960a36dccgki49g6dfg57
num = 0

【讨论】:

  • 如果只想打印特定的键值,什么是代码?我只想显示 id
  • 如果你只想要密钥,你可以用密钥替换 id 等等。
【解决方案2】:
foreach($json as $key => $value) {
    echo "$key: $value \n";
}

【讨论】:

  • 这只有在你有一个单层数组时才有效,从上面的输出他得到一个多层数组。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-15
  • 2012-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-07
相关资源
最近更新 更多