簡體   English   中英

展平json_decode創建的多維數組

[英]Flattening multidimensional array created by json_decode

我正在嘗試展平json_decode()返回的多維數組,但是出現問題。 我進行了一些研究,但所有解決方案似乎都跳過了我的一些數據。 如果我運行這個和比較echo “d數據var_dump()我肯定沒有得到一切,我不知道為什么。

這是我到目前為止的內容:

<?php
function array_flatten($array) { 
    if (!is_array($array)) { 
        return false; 
    }
    $result = array(); 
    foreach ($array as $key => $value) { 
        if (is_array($value)) { 
            $result = array_merge($result, array_flatten($value)); 
        } else { 
            $result[$key] = $value; 
        } 
    } 
    return $result; 
}
for ($x = 1; $x <= 1; $x++) {
    $response = file_get_contents('https://seeclickfix.com/api/v2/issues?page='.$x
                                 .'&per_page=1');
    // Decode the JSON and convert it into an associative array.
    $jsonDecoded = json_decode($response, true);
    $flat = array_flatten($jsonDecoded['issues']);
    foreach($flat as $item) {
        echo $item;
        echo "<br>";
    }
}
?>

文檔中所示array_merge將使用相同的鍵覆蓋值。 例如,在您發布的鏈接中,您將丟失一些網址。 您可以通過在展平的數組中創建唯一鍵來解決此問題。 例如,通過將前綴傳遞給函數:

function array_flatten($array, $prefix = '') { 
  if (!is_array($array)) { 
    return false; 
  } 
  $result = array(); 
  foreach ($array as $key => $value) { 
    if (is_array($value)) { 
      $result = array_merge($result, array_flatten($value, $prefix.'_'.$key)); 
    } else { 
      $result[$prefix.'_'.$key] = $value; 
    } 
  } 
  return $result; 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM