删除所有数字索引以仅具有关联数组

时间:2015-06-23 06:41:11

标签: php arrays

如果我在发出print_r()语句后有这样的数组:

//print_r($theArray)
array (size=5)
  0 => 
    array (size=1)
      'Animal' => string 'Dog' (length=3)

  1 => 
    array (size=1)
      'House' => string 'white house' (length=11)

  2 =>
    array (size=1)
      'Human' =>  
         array (size=3)
           'Africans' => string 'Nigroids' (length=8)
           'Europeans' => string 'Caucasoids' (length=8)
           'Asians' => string 'Mugoloids' (length=8)

如何删除所有数字索引,使上面的数组变为

array(
     'Animal' => string 'Dog' (length=3),
     'House' => string 'white house' (length=11),
     'Human' =>  
         array (size=3)
           'Africans' => string 'Nigroids' (length=8),
           'Europeans' => string 'Caucasoids' (length=8),
           'Asians' => string 'Mugoloids' (length=8)
    )

请帮忙吗?

3 个答案:

答案 0 :(得分:1)

一个foreach就够了

$new = array();
foreach($array as $arr) 
       $new  =  $new + $arr;
 print_r($new);

答案 1 :(得分:0)

Double foreach()可行:

<?php
    $array[]    =   array('Animal'=>"dog");
    $array[]    =   array('House'=>"white");
    $array[]    =   array('Human'=>array("Africans"=>"af","Europeans"=>"ca","Asians"=>"as"));

    foreach($array as $arr) {
            foreach($arr as $key => $data) {
                    $new[$key]  =   $data;
                }
        }

    print_r($new);
?>

给你:

Array
(
    [Animal] => dog
    [House] => white
    [Human] => Array
        (
            [Africans] => af
            [Europeans] => ca
            [Asians] => as
        )

)

答案 2 :(得分:0)

简单如下:

$theArray = call_user_func_array('array_merge', $theArray);

这相当于以下内容,只需使用任意数量的数组:

$theArray = array_merge($theArray[0], $theArray[1], $theArray[2], ...);

或者,为了一些功能性的乐趣:

$theArray = array_reduce($theArray, 'array_merge', []);

相当于:

$result = [];
foreach ($theArray as $array) {
    $result = array_merge($result, $array);
}
$theArray = $result;