Php 自定义数组多维值
我的代码有问题。例如,我有这样一个数组:Php 自定义数组多维值,php,Php,我的代码有问题。例如,我有这样一个数组: [ 'a' => ['f', 'g'], 'b' => ['h', 'i'], 'c' => ['j', 'k'] ] 我想将我的数组更改为如下所示: [ ['a' => 'f', 'b' => 'h', 'c' => 'j'], ['a' => 'g', 'b' => 'i', 'c' => 'k'] ] 我需要帮助来解决这个问题。谢谢我在本地电脑上测试了
[
'a' => ['f', 'g'],
'b' => ['h', 'i'],
'c' => ['j', 'k']
]
我想将我的数组更改为如下所示:
[
['a' => 'f', 'b' => 'h', 'c' => 'j'],
['a' => 'g', 'b' => 'i', 'c' => 'k']
]
我需要帮助来解决这个问题。谢谢我在本地电脑上测试了这个
<?php
$array = [
'a' => ['f', 'g'],
'b' => ['h', 'i'],
'c' => ['j', 'k']
];
$ultimate_array = array();
foreach($array as $key1 => $child_array)
{
foreach($child_array as $i => $key2)
{
if(empty($ultimate_array[$i])) $ultimate_array[$i] = array();
$ultimate_array[$i][$key1] = $key2;
}
}
print_r($ultimate_array);
?>
这是一个简单的演示:
<?php
$input = [
'a' => ['f', 'g'],
'b' => ['h', 'i'],
'c' => ['j', 'k']
];
$output = [];
foreach ($input as $key=>$entries) {
foreach ($entries as $entry) {
$output[$key][] = $entry;
}
}
var_dump($output);
因为什么奇怪的原因,你需要这样做?我想使用数组使它成为json。如果我使用上面的示例数组来转换为json,那么调用数据将很困难
<?php
$input = [
'a' => ['f', 'g'],
'b' => ['h', 'i'],
'c' => ['j', 'k']
];
$output = [];
array_walk($input, function($entries, $key) use (&$output) {
array_walk($entries, function($entry) use (&$output, $key) {
$output[$key][] = $entry;
});
});
var_dump($output);
array(3) {
["a"]=>
array(2) {
[0]=>
string(1) "f"
[1]=>
string(1) "g"
}
["b"]=>
array(2) {
[0]=>
string(1) "h"
[1]=>
string(1) "i"
}
["c"]=>
array(2) {
[0]=>
string(1) "j"
[1]=>
string(1) "k"
}
}