0

So, I have multidimensional array (for example):

array[1][22]['name']
array[1][33]['name']
array[2][44]['name']
array[3][55]['name']

I know last array key(it's ID) (for example - [44]), how can I find value of [name] for known key?

In my guess I need something like array_search, but for key and in multidimensional array...

2
  • Possible duplicate of How to search through multi level arrays looking for text (PHP) Commented Oct 22, 2015 at 14:59
  • There are plenty of builtin functions to search and manipulate multidimensional arrays. But your question is a bit unclear, I didn't get this part: I know last array key(it's ID) (for example - [44]) Commented Oct 22, 2015 at 15:02

4 Answers 4

2

Here's a simple way with PHP >= 5.5.0. This assumes there is only one key 44 in the array:

echo array_column($array, 44)[0]['name'];
// or
echo current(array_column($array, 44))['name'];

Earlier versions:

foreach($array as $k => $v) { if(isset($v[44])) echo $v[44]['name']; }
Sign up to request clarification or add additional context in comments.

Comments

1

You are better off changing your array structure:

$array = [
  22 => [ 'name' => 'A'],
  33 => [ 'name' => 'B'],
  44 => [ 'name' => 'C'],
  55 => [ 'name' => 'D'],
];

and simply write

$array[44]['name']

Comments

0

Wouldn't it be better to optimize your array for this search, for instance build another one with IDs as keys and references to the data as values?

When building your array you could:
$IDsIndex = array();
foreach(...) {
    $IDsIndex[$ID] = &$data;
}

and then:

$IDsIndex[44]['name'];

Comments

0

I have a function that seems to work for me. Let me know if you find it lacking. Note: It has not been tested for performance on massive arrays or objects.

function arrayKeySearch(array $haystack, string $search_key, &$output_value, int $occurence = 1){
    $result             = false;
    $search_occurences  = 0;
    $output_value       = null;
    if($occurence < 1){ $occurence = 1; }
    foreach($haystack as $key => $value){
        if($key == $search_key){
            $search_occurences++;
            if($search_occurences == $occurence){
                $result         = true;
                $output_value = $value;
                break;
            }
        }else if(is_array($value) || is_object($value)){
            if(is_object($value)){
                $value = (array)$value;
            }
            $result = arrayKeySearch($value, $search_key, $output_value, $occurence);
            if($result){
                break;
            }
        }
    }
    return $result;
}

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.