我正在尝试将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"
);
我无法弄清楚..请帮忙:)
答案 0 :(得分:3)
从5.5版开始,PHP有一个很棒的内置函数叫array_column(),可以让你做到
$newArray = array_column($array, 'value', 'name');
答案 1 :(得分:0)
这种问题每天都会出现。当在原始数组中循环并创建一个新数组非常简单时,为什么要强调找不到专门的函数呢?
// 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具有索引中原始数组的名称和值中原始数组的值。
答案 2 :(得分:0)
代码段:
$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;