我想用组合键将多维数组转换为单维数组,也许我的问题不明白,所以我举一个例子来解释:
我有array
,如下所示:
// JSON
{"a":{"a":{"a":1},"b":{"a":1},"c":{"a":1},"d":{"a":1},"e":{"a":1,"b":1,"c":1,"d":1},"f":{"a":1}}}
Array
(
[a] => Array
(
[a] => Array
(
[a] => 1
)
[b] => Array
(
[a] => 1
)
[c] => Array
(
[a] => 1
)
[d] => Array
(
[a] => 1
)
[e] => Array
(
[a] => 1
[b] => 1
[c] => 1
[d] => 1
)
[d] => Array
(
[a] => 1
)
)
)
我想要的东西
Array
(
[0] => '[a][a][a]'
[1] => '[a][b][a]'
[2] => '[a][c][a]'
[3] => '[a][d][a]'
[4] => '[a][e][a]'
[5] => '[a][e][b]'
[6] => '[a][e][c]'
[7] => '[a][e][d]'
[8] => '[a][f][a]'
)
希望可以理解
我尝试了很多方法但没有成功,请帮助
How to Flatten a Multidimensional Array?,此答案不是我的问题的解决方案,请比较
答案 0 :(得分:0)
<?php
$json = '{"a":{"a":{"a":1},"b":{"a":1},"c":{"a":1},"d":{"a":1},"e":{"a":1,"b":1,"c":1,"d":1},"f":{"a":1}}}';
$array = json_decode($json, true);
$returnarray = [];
$i = 0;
$main = array_keys($array);
foreach($array['a'] as $key => $val) {
$arr = [];
array_push($arr, $main[0]);
$keysarr = array_keys($val);
array_push($arr, $key);
if(count($keysarr) > 1) {
for($j = 0; $j < count($keysarr); $j++) {
array_push($arr, $keysarr[$j]);
$returnarray[$i] = $arr;
array_pop($arr);
$i++;
}
} else {
array_push($arr, $keysarr[0]);
$returnarray[$i] = $arr;
$i++;
}
}
echo "<pre>";
print_r($returnarray);
?>
答案 1 :(得分:0)
效率不高,但是如果您的数组与示例中显示的方式完全一样,那就去做吧。
<?php
$dataSource = array
(
'a' => array
(
'a' => array
(
'a' => 1
),
'b' => array
(
'a' => 1
),
'c' => array
(
'a' => 1
),
'd' => array
(
'a' => 2
),
'e' => array
(
'a' => 1,
'b' => 1,
'c' => 1,
'd' => 1
),
'f' => array
(
'a' => 1
)
)
) ;
echo "<pre>";
print_r($dataSource);
echo "</pre>";
$resultData = [];
foreach($dataSource as $key => $val)
{
foreach($val as $key1 => $val1)
{
foreach($val1 as $key2 => $val2)
{
$resultData[] = '['.$key.']['.$key1.']['.$key2.']';
}
}
}
echo "<pre>";
print_r($resultData);
echo "</pre>";
答案 2 :(得分:0)
这解决了我的问题,虽然棘手,但适用于我的情况:
$json = '{"a":{"a":{"a":1},"b":{"a":1},"c":{"a":1},"d":{"a":1},"e":{"a":1,"b":1,"c":1,"d":{"a":1}},"f":{"a":1}},"b":{"a":{"a":1}}}';
$data = json_decode($json, true);
function array_str($data = array()) {
$result = [];
$data = explode('&', urldecode(http_build_query($data)));
foreach ($data as $value) {
$main = explode('[', $value)[0];
$result[] = preg_replace('/' . $main . '/', '[' . $main . ']', explode('=', $value)[0], 1);
}
return $result;
}