FartMachine4U
FartMachine4U

Reputation: 115

PHP - converting array to multidimension

I have this array ($originalArray):

Array ( 
  [c] => 1 
  [d] => 2 
  [e] => 1
  [a] => 1 
)

and would like to convert it/create another a multidimensional which would look like:

Array ( 
  [0] => Array ( [name] => a [status] => 1 ) 
  [1] => Array ( [name] => c [status] => 1 )
  [2] => Array ( [name] => d [status] => 2 )
  [3] => Array ( [name] => e [status] => 1 ) 
)

Something like this I am thinking:

$new_array = array();
foreach ($originalArray as $key=>$val)
    {
    $new_array[] = array('name'=>$originalArray[$val],'status'=>$originalArray[$key]);
}

Upvotes: 0

Views: 54

Answers (3)

Srijith Vijayamohan
Srijith Vijayamohan

Reputation: 915

Your logic is right. May reduce the code by using $key, $value variables you get from the loop.

$new_array = array();
foreach ($originalArray as $key=>$val)
{
  $new_array[] = array('name'=>$val,'status'=>$key);
}

Upvotes: 1

hsz
hsz

Reputation: 152206

Try with:

$input  = array('c' => 1, 'd' => 2, 'e' => 1, 'a' => 1);
$output = array();

foreach ($input as $name => $status) {
  $output[] = array(
    'name'   => $name,
    'status' => $status
  );
}

Upvotes: 1

Explosion Pills
Explosion Pills

Reputation: 191729

It's even simpler than that:

$new_array[] = array("name" => $key, "status" => $val);

Upvotes: 1

Related Questions