[英]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. 我正在尝试展平
json_decode()
返回的多维数组,但是出现问题。 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. 如果我运行这个和比较
echo
“d数据var_dump()
我肯定没有得到一切,我不知道为什么。
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 . 如文档中所示 ,
array_merge
将使用相同的键覆盖值。 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.