如何通过循环动态多维数组为特定键生成数组路径?
How to generate array path for specific key by looping through dynamic multidimensional array?
我有一个动态多维数组如下:
$cityList = [
'AUS' => [
'VIC' => [
'population' => [ 'total' => '5M']
'Richmond' => [
'population' => [ 'total' => '0.15M']
]
],
'NSW' => [
'Carlton' => [
'population' => [ 'total' => '8M']
]
]
]
];
此处,列 人口 可能存在也可能不存在于所有维度上。但是,如果它存在,那么它将始终具有 total 作为上面的子数组。
现在,我需要遍历数组并生成所有到 population 的路径(如果存在的话)。
我写的代码如下:
public function fetchAllPopulation(array $cityList, $path = '', &$cityWithPopulation)
{
foreach ($cityList as $key => $city) {
if (is_array($city) && $key != 'population') {
$path .= $path == '' ? $key: "##$key";
$this->fetchAllPopulation($city, $path, $cityWithPopulation);
} else {
$population = $city['total'];
$cityWithPopulation[$path] = $population;
}
}
return $assetWithPathsAndIds;
}
预期输出:
[
'AUS##VIC' => '5M',
'AUS##VIC##Richmond' => '0.15M',
'AUS##NSW##Carlton' => '8M'
]
实际输出:
[
'AUS##VIC' => '5M',
'AUS##VIC##Richmond' => '0.15M',
'AUS##VIC##NSW##Carlton' => '8M' // this is incorrect
]
问题是如果任何列的维度超过 2,那么前一个键将附加到下一个键,如上所示。
对我的代码的任何反馈或更正将不胜感激。谢谢!
这样:
public function fetchAllPopulation(array $cityList, $path, &$cityWithPopulation)
{
foreach ($cityList as $key => $city) {
if (is_array($city) && $key != 'population') {
$subPath = $path . ($path == '' ? $key: "##$key");
$this->fetchAllPopulation($city, $subPath, $cityWithPopulation);
} else {
$population = $city['total'];
$cityWithPopulation[$path] = $population;
}
}
return $assetWithPathsAndIds;
}
我有一个动态多维数组如下:
$cityList = [
'AUS' => [
'VIC' => [
'population' => [ 'total' => '5M']
'Richmond' => [
'population' => [ 'total' => '0.15M']
]
],
'NSW' => [
'Carlton' => [
'population' => [ 'total' => '8M']
]
]
]
];
此处,列 人口 可能存在也可能不存在于所有维度上。但是,如果它存在,那么它将始终具有 total 作为上面的子数组。
现在,我需要遍历数组并生成所有到 population 的路径(如果存在的话)。
我写的代码如下:
public function fetchAllPopulation(array $cityList, $path = '', &$cityWithPopulation)
{
foreach ($cityList as $key => $city) {
if (is_array($city) && $key != 'population') {
$path .= $path == '' ? $key: "##$key";
$this->fetchAllPopulation($city, $path, $cityWithPopulation);
} else {
$population = $city['total'];
$cityWithPopulation[$path] = $population;
}
}
return $assetWithPathsAndIds;
}
预期输出:
[
'AUS##VIC' => '5M',
'AUS##VIC##Richmond' => '0.15M',
'AUS##NSW##Carlton' => '8M'
]
实际输出:
[
'AUS##VIC' => '5M',
'AUS##VIC##Richmond' => '0.15M',
'AUS##VIC##NSW##Carlton' => '8M' // this is incorrect
]
问题是如果任何列的维度超过 2,那么前一个键将附加到下一个键,如上所示。
对我的代码的任何反馈或更正将不胜感激。谢谢!
这样:
public function fetchAllPopulation(array $cityList, $path, &$cityWithPopulation)
{
foreach ($cityList as $key => $city) {
if (is_array($city) && $key != 'population') {
$subPath = $path . ($path == '' ? $key: "##$key");
$this->fetchAllPopulation($city, $subPath, $cityWithPopulation);
} else {
$population = $city['total'];
$cityWithPopulation[$path] = $population;
}
}
return $assetWithPathsAndIds;
}