开发者

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. Pul开发者_运维问答ling 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.


Using foreach, you can iterate through an array with variable indicies.

$array_of_moms = array();

foreach ($neighborhood AS $family) {
    $array_of_moms[] = $family['mom']; // append mom of each family to array
}


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
        )

)

http://codepad.org/xbnj5UmV

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜