我有一个表单数组:
$records = array(
array(
'id' => 2135,
'first_name' => 'John',
'last_name' => 'Doe',
),
array(
'id' => 3245,
'first_name' => 'Sally',
'last_name' => 'Smith',
),
array(
'id' => 5342,
'first_name' => 'Jane',
'last_name' => 'Jones',
),
array(
'id' => 5623,
'first_name' => 'Peter',
'last_name' => 'Doe',
)
);
我想要这样的输出:
修改
Array
( array('first_Name' => John),
array('first_Name'=> Sally),
array('first_Name'=> Jane),
array('first_Name'=> Peter)
);
这可以实现吗?
答案 0 :(得分:3)
由于您无法在数组中使用重复键,因此无法执行此操作。
以下是相关问题:How to allow duplicate keys in a PHP array?
本文解释了PHP如何在内部存储数组:http://nikic.github.io/2012/03/28/Understanding-PHPs-internal-array-implementation.html。
编辑后回答:
$arr = array();
foreach($records as $value) {
$arr[] = array('first_name' => $value['first_name']);
}
print_r($arr);
答案 1 :(得分:2)
你可以像这样实现你的(编辑过的)问题:
$new_array = array();
foreach($records as $record)
$new_array[] = array('first_Name'=>$records['first_name']);
答案 2 :(得分:1)
试试这个
$records = array(
array(
'id' => 2135,
'first_name' => 'John',
'last_name' => 'Doe',
),
array(
'id' => 3245,
'first_name' => 'Sally',
'last_name' => 'Smith',
),
array(
'id' => 5342,
'first_name' => 'Jane',
'last_name' => 'Jones',
),
array(
'id' => 5623,
'first_name' => 'Peter',
'last_name' => 'Doe',
)
);
$tmp = array('first_name' => '');
foreach ($records as &$record) {
$record = array_intersect_key($record, $tmp);
// or $record = array('first_name' => $record['first_name']);
}
unset($record);
var_dump($records);
答案 3 :(得分:1)
如果你想在数组中使用数组,那肯定会用索引键生成,就像这个
一样 Array
( '0' => array('first_Name' => John),
'1' => array('first_Name'=> Sally),
'2' => array('first_Name'=> Jane),
'3' => array('first_Name'=> Peter)
);
试试这个,
foreach($records as $record) {
$name_array[] = Array('first_Name' =>$record['first_name']);
}
print_r($name_array);
您的输出将是,
Array
(
[0] => Array
(
[first_Name] => John
)
[1] => Array
(
[first_Name] => Sally
)
[2] => Array
(
[first_Name] => Jane
)
[3] => Array
(
[first_Name] => Peter
)
)
答案 4 :(得分:0)
这是不可能的,因为在关联数组中不能有相同键的多个元素。
答案 5 :(得分:0)
你可以尝试这个
$arr_output = array();
foreach($records as $key=>$arr)
{
$arr_output['id'][] = $arr['id'];
$arr_output['first_name'][] = $arr['first_name'];
$arr_output['last_name'][] = $arr['last_name'];
}
print_r($arr_output['first_name']); // display all first names
print_r($arr_output); // display complete output array.
输出
Array
(
[id] => Array
(
[0] => 2135
[1] => 3245
[2] => 5342
[3] => 5623
)
[first_name] => Array
(
[0] => John
[1] => Sally
[2] => Jane
[3] => Peter
)
[last_name] => Array
(
[0] => Doe
[1] => Smith
[2] => Jones
[3] => Doe
)
)
<强> Demo 强>
答案 6 :(得分:0)
要获得所需的输出,您可以使用array_map
,尽管您可以使用array_column
获得类似的输出,这是PHP 5.5中的新功能。
array_map
(http://3v4l.org/v8Y8Z):<?php
$firstNames = array_map(function($record) {
return ['first_name' => $record['first_name']];
}, $records);
array_column
(http://3v4l.org/ohnGu):$firstNames = array_column($records, 'first_name');
注意:array_column
不会使用first_name
密钥创建子数组。