[英]How do I make a list of specific values in a PHP multidimensional array?
I have a multidimensional array like so: 我有一个这样的多维数组:
$neighborhood => array(
'the_smiths' => array(
'dad' => 'Donald',
'mom' => 'Mary',
'daughter' => 'Donna',
'son' => 'Samuel'
)
'the_acostas' => array(
'dad' => 'Diego',
'mom' => 'Marcela',
'daughter' => 'Dominga',
'son' => 'Sergio'
)
);
I would like to create another array (let's call it $array_of_moms
) of all the moms in the neighborhood. 我想为附近的所有妈妈创建另一个数组(我们称之为
$array_of_moms
)。 Pulling them all in separately is doable, but not practical (like so): 将它们全部分开是可行的,但不切实际(像这样):
$array_of_moms = array(
$neighborhood['the_smiths']['mom'],
$neighborhood['the_acostas']['mom'],
)
How do I create something like this: 我如何创建这样的东西:
$array_of_moms = $neighborhood['mom'];
$moms = array();
foreach($neighborhood as $family)
{
$moms[] = $family['mom'];
}
This'll iterate through each family in the array and add the mom to the new $moms
array. 这将遍历数组中的每个家庭,并将妈妈添加到新的
$moms
数组中。
If you can manipulate your array, you could: 如果可以操纵数组,则可以:
<?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);
?>
Which outputs: 哪个输出:
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
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.