简体   繁体   中英

Flattening multidimensional array created by json_decode

I'm trying to flatten a multidimensional array that was returned by json_decode() but I'm having issues. I've some research but all of the solutions seem to be skipping over some of my data. If I run this and compare the echo 'd data to var_dump() I'm definitely not getting everything and I'm not sure why.

Here is what I have so far:

<?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 will overwrite values with the same key, as you can see in the documentation . Eg in the link you posted, you will lose some urls. You could fix that by create unique keys in the flattened array. For example by passing a prefix to your function:

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; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM