我有一个这样的数组:
Array
(
[0] => Array
(
[0] => element 1
[1] => Array
(
[0] => white house history
[1] => white house historical association
[2] => white house hotel istanbul
[3] => white house high school
)
)
[1] => Array
(
[0] => element 2
[1] => Array
(
[0] => white kilt hose
[1] => white knight hose
[2] => white house kennels
[3] => white house kinsale
)
)
[2] => Array
(
[0] => element 3
[1] => Array
(
[0] => white house news
[1] => white house nannies
[2] => white house number
[3] => white house nominations
)
)
我想创建一个新数组,其中只包含每个数组中的元素:
[0] => white house history
[1] => white house historical association
[2] => white house hotel istanbul
[3] => white house high school
[4] => white kilt hose
[5] => white knight hose
[6] => white house kennels
[7] => white house kin sale
[8] => white house news
[9] => white house nannies
[10] => white house number
[11] => white house nominations
有人知道怎么做吗?
答案 0 :(得分:0)
<?php
$names = array();
foreach ($arr as $k => $v) {
if (! empty($v[1])) {
foreach ($v[1] as $elem) {
$names[] = $elem;
}
}
}
?>
<强>解释强>
您需要驻留在每个数组的第二部分中的所有元素。
循环主阵列。
转到子数组的第二部分,这些是您想要的名称。
只需将它们附加到空白(必需)数组,我们就可以得到输出。
答案 1 :(得分:0)
通常我会鼓励你先尝试一下,但为了教学,这里有一些评论代码:
$newArray = []; // use array() for PHP before 5.4, I think
foreach($oldArray as $subArray) { // process top-level elements
bool $firstElement = true; // flag to indicate if we've gone past 1 element yet
foreach($subArray as $element) { // process second-level elements
if(!firstElement && is_array($element)) { // look for arrays that come after first element
$newArray = array_merge($newArray, $element);
}
$firstElement = false; // unset the flag
}
}
编辑:澄清要求后,实现嵌套循环和$ firstElement标志