array_values recursive php

前端 未结 5 785
粉色の甜心
粉色の甜心 2020-12-10 16:12

Let\'s say I have an array like this:

Array
(
    [id] => 45
    [name] => john
    [children] => Array
    (
        [45] => Array
            (         


        
相关标签:
5条回答
  • 2020-12-10 16:40

    Try this ,

        function updateData($updateAry,$result = array()){
         foreach($updateAry as $key => $values){
          if(is_array($values) && count($values) > 0){
            $result[$key] = $this->_updateData($values,$values);
          }else{
            $result[$key] = 'here you can update values';
          }
         }
         return $result;
       }
    
    0 讨论(0)
  • 2020-12-10 16:44

    This should do it:

    function array_values_recursive($arr, $key)
    {
        $arr2 = ($key == 'children') ? array_values($arr) : $arr;
        foreach ($arr2 as $key => &$value)
        {
            if(is_array($value))
            {
                $value = array_values_recursive($value, $key);
            }
        }
        return $arr2;
    }
    
    0 讨论(0)
  • 2020-12-10 16:49

    You can used php fnc walk_array_recursive Here

    0 讨论(0)
  • 2020-12-10 16:50

    You use a recursive approach but you do not assign the return value of the function call $this->array_values_recursive($value); anywhere. The first level works, as you modify $arr in the loop. Any further level does not work anymore for mentioned reasons.

    If you want to keep your function, change it as follows (untested):

    function array_values_recursive($arr)
    {
      foreach ($arr as $key => $value)
      {
        if (is_array($value))
        {
          $arr[$key] = $this->array_values_recursive($value);
        }
      }
    
      if (isset($arr['children']))
      {
        $arr['children'] = array_values($arr['children']);
      }
    
      return $arr;
    }
    
    0 讨论(0)
  • 2020-12-10 16:50
    function array_values_recursive($arr)
    {
        $arr2=[];
        foreach ($arr as $key => $value)
        {
            if(is_array($value))
            {            
                $arr2[] = array_values_recursive($value);
            }else{
                $arr2[] =  $value;
            }
        }
    
        return $arr2;
    }
    

    this function that implement array_values_recursive from array like:

    array(   
       'key1'=> 'value1',   
       'key2'=> array (              
             'key2-1'=>'value-2-1',
             'key2-2'=>'value-2-2'
              )
    );
    

    to array like:

    array(
        0 => 'value1',
        1 => array (
               0 =>'value-2-1',
               1 =>'value-2-2'
              )
    );
    
    0 讨论(0)
提交回复
热议问题