php数组的多维数组键值


php array from multidimensional array keys values

入门问题。初始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
)

这是您可能需要的代码,其中$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
)

没有预制函数,只需创建一个新数组来保存在第一个级别上迭代的结果,然后用foreach提取第二个级别的键和值。有几种方法可以做到这一点,但这通常是我的做法。

$NewArray = array();
for($i = 0; $i <= count($ExistingArray); $i++){
   foreach($ExistingArray[$i] as $key => $val){
        $NewArray[$key] = $val;
   }
}