php - Remove all numeric index to have an assoc array only

184

If i have an array like this after issuing a print_r() statement:

//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)

how can i remove all numeric indices such that above array becomes

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)
    )

any help is please ?

314

Answer

Solution:

One foreach just enough

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

Answer

Solution:

As simple as:

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

This is equivalent to the following, just with an arbitrary number of arrays:

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

Alternatively, for some functional fun:

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

Which is equivalent to:

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

Answer

Solution:

Doubleforeach() would work:

<?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);
?>

Gives you:

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

)

People are also looking for solutions to the problem: php - Dynamic multidimensional array keys for class property

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.