将PHP数组格式从一种更改为另一种


Change PHP array format from one to another

我正在尝试将PHP数组从一种格式转换为另一种格式。

我的数组看起来像:

array (size=5)
  0 =>
    array (size=2)
      'name' => string 'userName' (length=8)
      'value' => string 'thename' (length=7)
  1 =>
    array (size=2)
      'name' => string 'email' (length=5)
      'value' => string 'email@email.com' (length=15)
  2 =>
    array (size=2)
      'name' => string 'password' (length=8)
      'value' => string 'thepassword' (length=11)
  3 =>
    array (size=2)
      'name' => string 'confirmPassword' (length=15)
      'value' => string 'thepassword' (length=11)
  4 =>
    array (size=2)
      'name' => string 'postcode' (length=8)
      'value' => string 'postcode' (length=8)

我需要将其重新格式化为:

array("userName" => "thename",
      "email" => "email@email.com",
      "password" => "thepassword",
      "confirmPassword" => "thepassword",
      "postcode" => "postcode"
     );

我就是想不通。。请帮助:)

自5.5版本以来,PHP有一个很棒的内置函数array_column(),可以让您执行

$newArray = array_column($array, 'value', 'name');

这类问题每天都会出现。当循环遍历原始数组并创建新数组非常简单时,为什么要强调寻找一个专门的函数来完成这项工作呢?

// Assume $old_array is the one you have that you are working with
$new_array = array();
foreach($old_array as $a)
    $new_array[$a['name']] = $a['value'];

就是这样。$new_array在索引中有原始数组的名称,在值中有原始阵列的值。

代码片段:

$result = array();
foreach($orig as $def) {
    $result[$def['name']] = $def['value'];
}

下面是一个完整的例子:

$orig = array (
    array (
      'name' => 'userName',
      'value' => 'thename',
    ),
    array (
      'name' => 'email',
      'value' => 'email@email.com',
    ),
    array (
      'name' => 'password',
      'value' => 'thepassword',
    ),
    array (
      'name' => 'confirmPassword',
      'value' => 'thepassword',
    ),
    array (
      'name' => 'postcode',
      'value' => 'postcode',
    ),
);
$result = array();
foreach($orig as $def) {
    $result[$def['name']] = $def['value'];
}
echo '<pre>'.PHP_EOL;
echo '<h3>Original Array</h3>'.PHP_EOL;
var_dump($orig);
echo '<h3>Resulting Array</h3>'.PHP_EOL;
var_dump($result);
echo '</pre>'.PHP_EOL;