我有一个多维数组,如下所示:
$neighborhood => array(
'the_smiths' => array(
'dad' => 'Donald',
'mom' => 'Mary',
'daughter' => 'Donna',
'son' => 'Samuel'
)
'the_acostas' => array(
'dad' => 'Diego',
'mom' => 'Marcela',
'daughter' => 'Dominga',
'son' => 'Sergio'
)
);
我想创建另一个数组(让我们称之为$array_of_moms
(,它包含附近所有的妈妈。将它们单独放入是可行的,但不实用(就像这样(:
$array_of_moms = array(
$neighborhood['the_smiths']['mom'],
$neighborhood['the_acostas']['mom'],
)
我如何创建这样的东西:
$array_of_moms = $neighborhood['mom'];
$moms = array();
foreach($neighborhood as $family)
{
$moms[] = $family['mom'];
}
这将遍历数组中的每个族,并将mom添加到新的$moms
数组中。
使用foreach,您可以遍历具有可变标记的数组。
$array_of_moms = array();
foreach ($neighborhood AS $family) {
$array_of_moms[] = $family['mom']; // append mom of each family to array
}
如果你可以操作你的数组,你可以:
<?php
$neighborhood = array(
'families' => array(
'the_smiths' => array(
'dad' => 'Donald',
'mom' => 'Mary',
'daughter' => 'Donna',
'son' => 'Samuel'
),
'the_acostas' => array(
'dad' => 'Diego',
'mom' => 'Marcela',
'daughter' => 'Dominga',
'son' => 'Sergio'
)
)
);
foreach ($neighborhood['families'] as $family => $folks) {
$neighborhood['moms'][] = $folks['mom'];
}
print_r($neighborhood);
?>
哪个输出:
Array
(
[families] => Array
(
[the_smiths] => Array
(
[dad] => Donald
[mom] => Mary
[daughter] => Donna
[son] => Samuel
)
[the_acostas] => Array
(
[dad] => Diego
[mom] => Marcela
[daughter] => Dominga
[son] => Sergio
)
)
[moms] => Array
(
[0] => Mary
[1] => Marcela
)
)
http://codepad.org/xbnj5UmV