0

I have an interesting task which can not handle. I have an PHP array that is generated automatically and randomly once a multi-dimensional, associative or mixed.

$data['sport']['basketball']['team']['player']['position']['hand']['name']['finalelement']
$data['sport']['basketball']['team']['player'][0]['position']['hand']['name']['finalelement']
$data['sport']['basketball']['team']['player'][0]['position']['hand']['name'][0]['finalelement']
$data['sport']['basketball']['team']['player']['position']['hand']['name'][0]['finalelement']

The goal is, no matter whether it is multidimensional or associative get to the final element. There is a simple way that has few if conditions. But I want to ask if you have an idea if there is any more intreresen way?

1
  • The deepest is always stored with finalelement key? Commented Mar 23, 2017 at 13:11

2 Answers 2

2

you may use array_walk_recursive as follows :

$data['sport']['basketball']['team']['player']['position']['hand']['name']['finalelement'] = 'e1';
$data['sport']['basketball']['team']['player'][0]['position']['hand']['name']['finalelement'] = 'e2';
$data['sport']['basketball']['team']['player'][0]['position']['hand']['name'][0]['finalelement'] = 'e3';
$data['sport']['basketball']['team']['player']['position']['hand']['name'][0]['finalelement'] = 'e4';

$list = [];
array_walk_recursive($data, function ($value, $key) use (&$list) {
    $list[] = $value;
});

print_r($list);

This will Output the following:

Array (
    [0] => e1
    [1] => e4
    [2] => e2
    [3] => e3
)
Sign up to request clarification or add additional context in comments.

1 Comment

This is the simplest solution.
2

Next code returns first deepest value that is not an array:

$data['sport']['basketball']['team']['player']['position']['hand']['name'][0]['finalelement'] = 'end';

$current = $data;

while (is_array($current)) {
    $current = array_values($current)[0];
}

print $current; // end

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.