PHP多维数组怎么转换成二维数组

PHPz
Release: 2021-12-30 15:03:28
Original
4768 people have browsed it

PHP多维数组转换成二维数组的方法:首先创建需要转换成二维数组的多维数组;然后使用“array_merge”函数以及“foreach”循环遍历等方法将指定多维数组转成二维数组即可。

PHP多维数组怎么转换成二维数组

PHP多维数组怎么转换成二维数组?

php 多维数组转二维数组

   $list =array(
             "money"=>"255.00",
             "id"=>"1",
             "child"=>[
                         array(
                           "money"=>"380.00",
                           "id"=>"5",
                           "child"=>[
                              array(
                                 "money"=>"0.00",
                                 "id"=>"7",
                              ),
                              array(
                                 "money"=>"0.00",
                                 "id"=>"4",
                              )
                           ]
                         )

                      ]
            );
Copy after login

利用格式化打印出来

array(3) {
  ["money"]=>
  string(6) "255.00"
  ["id"]=>
  string(1) "1"
  ["child"]=>
  array(1) {
    [0]=>
    array(3) {
      ["money"]=>
      string(6) "380.00"
      ["id"]=>
      string(1) "5"
      ["child"]=>
      array(2) {
        [0]=>
        array(2) {
          ["money"]=>
          string(4) "0.00"
          ["id"]=>
          string(1) "7"
        }
        [1]=>
        array(2) {
          ["money"]=>
          string(4) "0.00"
          ["id"]=>
          string(1) "4"
        }
      }
    }
  }
}
Copy after login

例如将多维数组转成二维数组:

$lis = array();
$liss['money'] = $list['money'];
$liss['id'] = $list['id'];

//分解最终用$lis[]存储
$lis[] = $liss;
$li = ssb($list['child']);
$lis = array_merge($lis,$li);
function ssb($aa){
    $sb = array();
    foreach($aa as $v){
        $arr = array();
        $arr['money'] = $v['money']; 
        $arr['id'] = $v['id']; 
        $sb[] = $arr;
        if($v['child']){
            $sbb = ssb($v['child']);
            $sb = array_merge($sb,$sbb);
        }
    }
    return $sb;
}
 var_dump($lis);
Copy after login

运行结果如下:

array(4) {
  [0]=>
  array(2) {
    ["money"]=>
    string(6) "255.00"
    ["id"]=>
    string(1) "1"
  }
  [1]=>
  array(2) {
    ["money"]=>
    string(6) "380.00"
    ["id"]=>
    string(1) "5"
  }
  [2]=>
  array(2) {
    ["money"]=>
    string(4) "0.00"
    ["id"]=>
    string(1) "7"
  }
  [3]=>
  array(2) {
    ["money"]=>
    string(4) "0.00"
    ["id"]=>
    string(1) "4"
  }
}
Copy after login

更多相关知识,请访问PHP中文网

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template