Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove the first row from a 2d array and use those values as keys for each subsequent row

I am having this array :

array(
    0 => array("name", "address", "city"), 
    1=> array( "anoop", "palasis", "Indore"),
    2=> array( "ravinder", "annapurna", "Indore")
)

and I want to make this array in this way :

array( 
    0 => array("name" = >"anoop" , "address" = >"palasia", "city" = >"Indore"),
    1 => array("name" = >"ravinder" , "address" = >"annapurna", "city" = >"Indore")
)
like image 755
Ravinder Singh Avatar asked Aug 31 '25 16:08

Ravinder Singh


2 Answers

The modern way is:

$data = array_column($data, 'value', 'key');

In your case:

$data = array_column($data, 1, 0);
like image 145
Mycelin Avatar answered Sep 02 '25 06:09

Mycelin


Use array_combine. If $array contains your data

$result = array(
             array_combine($array[0], $array[1]),
             array_combine($array[0], $array[2])
          );

In general

$result = array();
$len = count($array);
for($i=1;$i<$len; $i++){
    $result[] = array_combine($array[0], $array[$i]);
}
like image 37
Shiplu Mokaddim Avatar answered Sep 02 '25 05:09

Shiplu Mokaddim