0

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) ...I.E.

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.

2
  • 2
    Maybe you want to flatten the array first, then use array_unique. Commented Nov 16, 2015 at 18:27
  • oh i think you are right. i will try array_values then array_unique. Commented Nov 16, 2015 at 18:33

4 Answers 4

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Add array_values() to reindex the array
1

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.

1 Comment

I accept this answer because it seems to be the least overhead and closest to intention for this case but the other answers are all relevant.
1

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
)

Comments

1

Yet another option:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.