【问题标题】:Split array values into multi dimensional array PHP将数组值拆分为多维数组 PHP
【发布时间】:2018-07-31 03:12:50
【问题描述】:

我有这个数组:

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

如何把上面的数组变成这个:

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

【问题讨论】:

标签: php arrays


【解决方案1】:

你可以使用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 是一个活生生的例子,说明了上述解决方案。

【讨论】:

    【解决方案2】:

    此代码将执行您想要的操作。它依次处理输入数组中的每个条目,并使用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
            )
    
    )
    

    【讨论】:

    • 不是我,但我明白为什么,我也想过这样做。您对代码没有任何解释或评论。这不是一个正确的答案
    • @Andreas 公平评论。有点匆忙。我已经添加了解释。
    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        【解决方案5】:

        使用array_map()

        $array = ['SecRuleEngine On', 'SecRequestBodyAccess On'];
        
        $new_array = array_map(function($item){ return explode(' ', $item); },  $array);
        
        print_r($new_array);
        

        【讨论】:

          猜你喜欢
          • 2017-12-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-05-04
          • 1970-01-01
          相关资源
          最近更新 更多