将数组值拆分为多维数组PHP

时间:2018-07-31 03:12:51

标签: php arrays

我有这个数组:

Array ( 
    [0] => SecRuleEngine On 
    [1] => SecRequestBodyAccess On
)

如何将上面的数组变成这样:

Array ( 
    [0] => 
        Array ( 
            [0] => SecRuleEngine 
            [1] => On
        ) 
        [1] => Array ( 
            [0] => SecRequestBodyAccess 
            [1] => On
        )
   )

5 个答案:

答案 0 :(得分:3)

您可以使用array_map来达到这样的效果,如下所示:

<?php
    # The initial array with its string elements.
    $array = ["SecRuleEngine On", "SecRequestBodyAccess On"];

    # Explode each element at the space producing array with 2 values.
    $new_array = array_map(function ($current) {
        return explode(" ", $current);
    }, $array);

    # Print the new array.
    var_dump($new_array);
?>

Here是演示上述解决方案的实时示例。

答案 1 :(得分:0)

此代码将执行您想要的操作。它依次处理输入数组中的每个条目,并使用explode将每个值转换为两个值的数组,第一个是输入值在空间左侧的一部分,第二个是在右侧空间的一部分,即'SecRuleEngine On'转换为['SecRuleEngine', 'On']

$input = array('SecRuleEngine On', 'SecRequestBodyAccess On');
$output = array();
foreach ($input as $in) {
    $output[] = explode(' ', $in);
}
print_r($output);

输出:

Array
(
    [0] => Array
        (
            [0] => SecRuleEngine
            [1] => On
        )

    [1] => Array
        (
            [0] => SecRequestBodyAccess
            [1] => On
        )

)

答案 2 :(得分:0)

这将为您提供所需的确切结果。只需尝试:

$input = ['SecRuleEngine On', 'SecRequestBodyAccess On'];
$output = [];
foreach($input as $item){
    array_push($output,explode(' ',$item));
}

print_r($output);

答案 3 :(得分:-1)

您必须遍历每个项目,然后使用它创建一个新数组:

$input = ['SecRuleEngine On', 'SecRequestBodyAccess On'];
$output = [];
foreach($input as $item)
{
    $keyval = explode(' ', $item);
    $output[] = [$keyval[0]=>$keyval[1]];
}

答案 4 :(得分:-1)

使用array_map()

$array = ['SecRuleEngine On', 'SecRequestBodyAccess On'];

$new_array = array_map(function($item){ return explode(' ', $item); },  $array);

print_r($new_array);