zoukankan      html  css  js  c++  java
  • PHP提取多维数组的键值

    1.利用递归对多维数组的键进行升序,并提取多维数组的键值对

    <?php
    $arr = [
        'name'=>'ll',
        'info'=>[
            'time'=>'2022',
            'order'=>[
    
                'suborder'=>[
                    'test2'=>['type'=>'O1','orderId'=>'093232'],
                    'test1'=>['orderId'=>'393l93','type'=>'02'],
                ],
                'id'=>1,
            ]
        ],
        'payDate'=>'2021'
    ];
    
    /*
     *@param mixed $arr 多维数组|键值     
    *@param $key_str string 本次递归的key
    *@param $res string 最终结果
    */ function getMutilArrKeysAndValues(&$arr,$key_str='',&$res=''){ //无效数组,退出 if(empty($arr) && empty($key_str)) return; //如果是键值,直接将键($key_str)和键值$arr通过'='连接,并返回该键值对 if(!is_array($arr)) return $key_str.'='.$arr.'&'; //根据键升序排序 ksort($arr); foreach ($arr as $key => &$value){ //保存本次调用函数时传入的键$key_str $temp1 = $key_str; if($key_str=='') $key_str=$key; else $key_str = $key_str.'.'.$key; if(is_array($value)) { //根据键升序排序 ksort($arr[$key]); //遍历数组里的每个键值对 foreach ($value as $key2 => $value2) { $temp =$key_str.'.'.$key2; //再一次遍历$value里的键值对 $key_value_str = getMutilArrKeysAndValues($value2, $temp,$res); $res .= $key_value_str; } } else{ //如果当前key的键值不是数组,直接通过‘=’连接 $key_value_str = $key_str.'='.$value.'&'; $res .= $key_value_str; } $key_str = $temp1; }
    unset($value); }
    $res = ''; getMutilArrKeysAndValues($arr,'',$res); print_r($res); $arr2=['name'=>'Li']; $res2=''; getMutilArrKeysAndValues($arr2,'',$res2); print(" "); print ($res2);
  • 相关阅读:
    京东白条
    Linux命令(40)rm 命令
    Linux命令(39)rmdir 命令
    Linux命令(38)pstree命令
    Linux命令(37)type命令
    Linux命令(36)help命令
    Linux命令(35)du命令
    CentOS7修改主机名
    Linux命令(34)tac命令
    Linux命令(33)cat命令
  • 原文地址:https://www.cnblogs.com/indifferent/p/14402619.html
Copyright © 2011-2022 走看看