PHP Splitting an Array into two arrays - keys array and values array

后端 未结 6 1420
夕颜
夕颜 2020-12-14 08:52

Is there an easy way to split an array into two arrays, one consisting of all the keys and the other consisting of all the values? This would be a reverse to the action of

6条回答
  •  醉梦人生
    2020-12-14 09:47

    function array_split($data)
    {
      $x = 0;//Counter to ensure accuracy
      $retArray[0] = array();//Array of Keys
      $retArray[1] = array();//Array of Values
    
      foreach($data as $key => $value)
      {
        $retArray[0][$x] = $key;
        $retArray[1][$x] = $value;
        $x++;
      }
    
      RETURN $retArray;
    }
    
    $data = array("key" => "value", "key2" => "value2");
    
    $splitData = array_split($data);
    
    //print_r($splitData[0]);//Output: Array ( [0] => key [1] => key2 ) 
    //print_r($splitData[1]);//Output: Array ( [0] => value [1] => value2 ) 
    
    print_r($splitData);
    //Output:
    /*
    Array
    (
        [0] => Array
            (
                [0] => key
                [1] => key2
            )
    
        [1] => Array
            (
                [0] => value
                [1] => value2
            )
    
    )
    */
    

提交回复
热议问题