请求您如何将以下数组转换为单个数组的帮助,我尝试了所有这些方法:
array_column($testarray, "Name") ,
array_merge($array, , $testarray),
array_map('current', $$testarray[0])
,但似乎没有任何效果。基本上,我需要使用implode(“','”,Name)将数组值作为字符串传递,以便数组值如下所示:
T : 'Name1','Name2'
D : 'Name11','Name21'
P : 'Name111','Name211'
原始数组
Array
(
[T] => Array
(
[0] => Array
(
[Name] => Name1
)
[1] => Array
(
[Name] => Name2
)
)
[D] => Array
(
[0] => Array
(
[Name] => Name11
)
[1] => Array
(
[Name] => Name21
)
)
[P] => Array
(
[0] => Array
(
[Name] => Name111
)
[1] => Array
(
[Name] => Name211
)
)
)
预期数组
T:
Name: Name1
Name2
D:
Name: Name11
Name21
P:
Name: Name111
Name211
来自 酒
答案 0 :(得分:0)
使用GitHub page和array_column()的最简单解决方案
$keys = array_keys($array); //get keys
foreach($keys as $key){ //iterate over keys
echo $key.': '. implode(',',array_column($array[$key],'Name'))."\n";
}
输出:-implode()
答案 1 :(得分:0)
您可以使用array_map
和array_column
展平数组:
$newarr = array_map(function ($v) { return array_column($v, 'Name'); }, $array);
print_r($newarr);
这给出了:
Array
(
[T] => Array
(
[0] => Name1
[1] => Name2
)
[D] => Array
(
[0] => Name11
[1] => Name21
)
[P] => Array
(
[0] => Name111
[1] => Name211
)
)
然后,您可以输出包含每个字符串的数组作为键结果的键:
foreach ($newarr as $key => $arr) {
echo "$key: " . implode(',', $arr) . "\n";
}
输出:
T: Name1,Name2
D: Name11,Name21
P: Name111,Name211
答案 2 :(得分:0)
尝试这个
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;
}
答案 3 :(得分:0)
$arr = [
'T' => [['Name' => 'Name1'], ['Name' => 'Name2']],
'D' => [['Name' => 'Name11'], ['Name' => 'Name11']],
'P' => [['Name' => 'Name111'], ['Name' => 'Name211']]
];
array_walk($arr,function(&$v, $k){
$v = ['Name' => array_column($v, 'Name')];
});
print_r($arr);
输出:
Array
(
[T] => Array
(
[Name] => Array
(
[0] => Name1
[1] => Name2
)
)
[D] => Array
(
[Name] => Array
(
[0] => Name11
[1] => Name11
)
)
[P] => Array
(
[Name] => Array
(
[0] => Name111
[1] => Name211
)
)
)