我有一个包含许多键和值对的数组。我想用php数组中的一个键获取所有值。
我的结果如
$seat=[
(int) 0 => [
(int) 0 => 'A_1',
(int) 1 => 'A_2',
(int) 2 => 'A_3',
(int) 3 => 'A_4'
],
(int) 1 => [
(int) 0 => 'B_1',
(int) 1 => 'B_2',
(int) 2 => 'B_3'
]
]
我想改变如下语法。
$seat=[
(int) 0 => [
(int) 0 => 'A_1',
(int) 1 => 'A_2',
(int) 2 => 'A_3',
(int) 3 => 'A_4'
(int) 4 => 'B_1',
(int) 5 => 'B_2',
(int) 6 => 'B_3'
]
]
谢谢大家:
答案 0 :(得分:2)
试试这个,
<?php
$result = array();
$seat=array(
"0" => array("0" => 'A_1',"1" => 'A_2',"2" => 'A_3',"3" => 'A_4'),
"1" => array("0" => 'B_1',"1" => 'B_2',"2" => 'B_3'),
"2" => array("0" => 'C_1',"1" => 'C_2',"2" => 'C_3'));
for($i=0;$i<count($seat);$i++){
$result = array_merge($result,$seat[$i]);
}
echo "<pre>";print_r($result);
?>
<强> 输出 强>
Array
(
[0] => A_1
[1] => A_2
[2] => A_3
[3] => A_4
[4] => B_1
[5] => B_2
[6] => B_3
[7] => C_1
[8] => C_2
[9] => C_3
)
答案 1 :(得分:2)
只需使用array_merge
功能。
$result = call_user_func_array('array_merge', $seat);
工作演示: http://phpio.net/s/1tx5
答案 2 :(得分:1)
你可以这样做:
function flattenArray($arr) {
$toflat = array($arr);
$res = array();
while (($r = array_shift($toflat)) !== NULL) {
foreach ($r as $v) {
if (is_array($v)) {
$toflat[] = $v;
} else {
$res[] = $v;
}
}
}
return $res;
}
$newArray = array(flattenArray($array1)); // This will be your desired result
<强>输出:强>
// So for example, if you pass array to flatternArray($array) method:
$array = array:2 [
0 => array:3 [
0 => 1
1 => 2
2 => 3
]
1 => array:3 [
0 => 4
1 => 5
2 => 6
]
]
// then $newArray will results in:
array:1 [
0 => array:6 [
0 => 1
1 => 2
2 => 3
3 => 4
4 => 5
5 => 6
]
]
希望这有帮助!
答案 3 :(得分:0)
由于您的输入是索引数组,因此您只需将结构展平(使用经典的splat&merge技术),然后将合并的结构推入一个空数组即可获得所需的结果(无需循环)。
代码:(Demo)
$seat = [
['A_1', 'A_2', 'A_3', 'A_4'],
['B_1', 'B_2', 'B_3'],
['C_1']
];
var_export(
[array_merge(...$seat)]
);
输出:
array (
0 =>
array (
0 => 'A_1',
1 => 'A_2',
2 => 'A_3',
3 => 'A_4',
4 => 'B_1',
5 => 'B_2',
6 => 'B_3',
7 => 'C_1',
),
)