来自多维数组键值的php数组 [英] php array from multidimensional array keys values
本文介绍了来自多维数组键值的php数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
初学者问题。初始php数组是多维的,内部包含数组。
Beginner question. Initial php array is multidimensional with arrays inside. Take a look.
Array
(
[0] => Array
(
[textkey] => text
[file] => file.txt
)
[1] => Array
(
[anotherkey] => another text
[file] => file2.xml
)
[2] => Array
(
[text_success] => Success
[newfile] => scope.txt
))
如何用foreach或其他方式重建它?
How to rebuild it with foreach or other way? Is any function to rebuild array to?
Array
(
[textkey] => text
[file] => file.txt
[anotherkey] => another text
[file] => file2.xml
[text_success] => Success
[newfile] => scope.txt
)
推荐答案
这是您可能想要的代码,其中 $ array
=上面指定的数组。
This is the code you may want where $array
= to the array you specified above.
$newArray = [];
foreach($array as $segment) {
foreach($segment as $key => $value) {
$newArray[$key] = $value;
}
}
print_r($newArray);
这是输出:
Array
(
[textkey] => text
[file] => file2.xml
[anotherkey] => another text
[text_success] => Success
[newfile] => scope.txt
)
但是,有一个问题。 file
键均未显示,因为单个键不能在数组中多次使用。要解决该问题,您可以为文件密钥分配一个简单的数组,其文件名如下:
But, there is a problem. Both the file
keys are not shown, because a single key cannot be used multiple times in an array. To get over that issue, you can assign a simple array to the file key with the file names like this:
$newArray = [];
foreach($array as $segment) {
foreach($segment as $key => $value) {
if($key == 'file') {
$newArray['file'][] = $value;
} else {
$newArray[$key] = $value;
}
}
}
print_r($newArray);
这给出了输出:
Array
(
[textkey] => text
[file] => Array
(
[0] => file.txt
[1] => file2.xml
)
[anotherkey] => another text
[text_success] => Success
[newfile] => scope.txt
)
这篇关于来自多维数组键值的php数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文