简体   繁体   中英

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. 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.

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM