PHP - 将数组转换为多维

时间:2014-01-23 15:06:46

标签: arrays multidimensional-array

我有这个数组($originalArray):

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

并想转换它/创建另一个多维,看起来像:

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

我在想这样的事情:

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

3 个答案:

答案 0 :(得分:1)

它比那更简单:

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

答案 1 :(得分:1)

尝试:

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

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

答案 2 :(得分:1)

你的逻辑是正确的。可以通过使用从循环中获得的$ key,$ value变量来减少代码。

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