初学者问题。最初的php数组是多维的,里面有数组。看一看。
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或其他方式重建它?是否有任何重建数组的函数?
Array
(
[textkey] => text
[file] => file.txt
[anotherkey] => another text
[file] => file2.xml
[text_success] => Success
[newfile] => scope.txt
)
答案 0 :(得分:0)
这是您可能需要的代码$array
=您在上面指定的数组。
$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
键都没有显示,因为单个键不能在数组中多次使用。要解决该问题,您可以使用如下文件名将简单数组分配给文件密钥:
$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
)
答案 1 :(得分:-1)
没有预制功能,但只需创建一个新数组来保存迭代在第一级上的结果,然后用foreach拉出第二级的键和值。有几种方法可以做到这一点,但这通常是我如何去做的。
$NewArray = array();
for($i = 0; $i <= count($ExistingArray); $i++){
foreach($ExistingArray[$i] as $key => $val){
$NewArray[$key] = $val;
}
}