简体   繁体   English

php如何将多维数组转换为单数组

[英]php how to convert multi-dimensional array to single array

I have below result from MySQL, PDO search - but I am not able to find suitable answer to make the arrays - to single array, insted of branched array.我有以下来自 MySQL、PDO 搜索的结果 - 但我无法找到合适的答案来制作数组 - 到单个数组,插入分支数组。

   <?php

$dataResult = array("abcdef", "People 1 - 123-456-7890
People 2 - 
People 3 - Abcdef Jack
People 4 _ Defjkl Smack ");


foreach($dataResult as $result){
    if(strstr($result, PHP_EOL)){
        $dataResultArray[] = explode(PHP_EOL, $result);
    } else {
        $dataResultArray[] = $result;
    }

    
}
print_r($dataResultArray);

I am expecting the below result, against what I get is below.我期待以下结果,而我得到的结果如下。

Expected:预期的:

abcdef
People 1 - 123-456-7890
People 2 - 
People 3 - Abcdef Jack
People 4 _ Defjkl Smack

Output:输出:

Array
(
    [0] => abcdef
    [1] => Array
        (
            [0] => People 1 - 123-456-7890
            [1] => People 2 - 
            [2] => People 3 - Abcdef Jack
            [3] => People 4 _ Defjkl Smack 
        )

)

PHP have a nice function for this case: array_walk_recursive :对于这种情况,PHP 有一个很好的函数: array_walk_recursive

// your multi-dimensional-array
$array = [
    'item1' => 'value1',
    'item2' => 'value2',
    'item3' => [
        'item3a' => 'value3',
    ],
    'item4' => [
        [
            'item4a' => [
                'value4',
                'value5',
            ],
        ]
    ]
];

array_walk_recursive($array, function($a) use (&$new) { $new[] = $a; });
print_r($new);

output输出

Array
(
    [0] => value1
    [1] => value2
    [2] => value3
    [3] => value4
    [4] => value5
)

You can use recusice function to convert multidimensional arrays to single array.您可以使用 recusice 函数将多维数组转换为单个数组。


function filter($array)
{
    static $newArray;
    if (is_array($array)):
        array_map('filter', $array);
    else:
        $newArray[] = $array;
    endif;

    return $newArray;
}


$array = [
    'isim' => 'Şahin',
    'soyisim' => 'ERSEVER',
    'yabanci_dil' => [
        'tr' => 'Türkçe',
    ],
    'languages' => [
        [
            'php' => [
                'codeigniter',
                'laravel',
                'symfony'
            ],
            'javascript' => [
                'vuejs',
                'react' => [
                    'react',
                    'react-native'
                ]
            ]
        ]
    ]
];


print_r(filter($array));

Result:结果:

Array
(
    [0] => Şahin
    [1] => ERSEVER
    [2] => Türkçe
    [3] => codeigniter
    [4] => laravel
    [5] => symfony
    [6] => vuejs
    [7] => react
    [8] => react-native
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM