简体   繁体   中英

PHP to get array_values from 2D array

I have a 2D array like

attendee_programs = [1 =>[100,101],
                     2 =>[100,101,102]
                    ];

I want to get array_values() and array_unique() but only for the nested elements (sorry, not sure what the terminology is) ...IE

programs = [100,101,102];

Is there a php function for this? or do I need to loop through and assemble it manually?

Edit: All of the answers are very helpful and have shown me something new. Sorry I can only accept one.

You could use a clever combination of array_unique, array_reduce and array_merge to achieve this:

$a = array_unique(array_reduce($attendee_programs, 'array_merge', []));

Doing this might be end in an array with some gaps in the indizes - if you need gaples array keys, you have to add array_values at the end

$a = array_values($a);

You can use:

call_user_func_array('array_merge', array_values($attendee_programs));

to get values of nested array.

array_unique(call_user_func_array('array_merge', array_values($attendee_programs)));

to get unique values.

Solution:

function flatten($array)
{
    $rit = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));

    return iterator_to_array($rit, true);
}

echo '<pre>';
print_r(flatten($attendee_programs));

Result:

Array
(
    [0] => 100
    [1] => 101
    [2] => 102
)

Yet another option:

$flat = array();
array_walk_recursive($attendee_programs, function($value) use (&$flat) {
    $flat[] = $value;
});
$flat = array_unique($flat);

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