【问题标题】:PHP json processing into arrayPHP json 处理成数组
【发布时间】:2014-11-26 18:14:22
【问题描述】:

我正在尝试从这个 JSON 中解析出一个包含所有数字的数组:

[{"page":1,"threads":[{"no":20783566,"last_modified":1417023255},{"no":20789075,"last_modified":1417023250},{"no":20777699,"last_modified":1417023250}]},{"page":2,"threads":[{"no":20753588,"last_modified":1417023105},{"no":20784845,"last_modified":1417023103},{"no":20789489,"last_modified":1417023099},{"no":20788012,"last_modified":1417023074}]}]

这是我目前所拥有的:

$array = json_decode($rawjson, true);

$threads = array();
$threadids = array();

for ($i = 0; $i < count($array); ++$i) {
    array_push($threads, $array[$i]['threads']);
}

for ($i = 0; $i < count($threads); ++$i) {
    array_push($threadids, $threads[$i]['no']);
}

我知道第一个 for 语句不像它应该的那样工作,我需要 array_push 不在原始数组中创建一个数组,但我不知道如何去做。 我无法让第二个 for 语句工作,因为我需要在每个数组中循环...

我想要的最终结果是一个包含 no 值的数组。我不想要任何数组格式。如果有人知道这样做的更好方法,请告诉我。

谢谢!

【问题讨论】:

    标签: php arrays json formatting


    【解决方案1】:

    我想你想要的是……

    $array = json_decode($rawjson, true);
    
    $threads = array();
    $threadids = array();
    
    for ($i = 0; $i < count($array); ++$i) {
      array_push($threads, $array[$i]['threads']);
    }
    
    for ($i = 0; $i < count($threads); ++$i) {
      foreach ($threads[$i] as $thread) {
        array_push($threadids, $thread['no']);
      }
    }
    

    使用print_r 查看您的阵列是什么样的。它会挽救你的生命!

    更好的是......(我个人更喜欢在这些类型的情况下使用 foreach)

    $array = json_decode($rawjson, true);
    
    $threads = array();
    $threadids = array();
    
    foreach ($array as $page) {
        array_push($threads, $page['threads']);
    }
    
    foreach($threads as $temp) {
      foreach ($temp as $thread) {
        array_push($threadids, $thread['no']);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多