0

I have an array like this, made of arrays with pairs of ids and names:

$myarray
: array = 
  0: array = 
    53: string = Robert  
  1: array = 
    28: string = Carl  
  2: array = 
    32: string = Anna 
  3: array = 
    84: string = Mary  
  4: array = 
    59: string = Daniel   

At certain point of my php script I'll get an id, and from this id I will need the name.

I know that with an unidimensional array is a simple as $myarray[$id] but with the one above, how can I do it??

Thanks a lot!!

1
  • 1
    What would you $id look like? In a multi-array, you just use more []. Like: $myarray[0][53] would be "Robert". Commented Jul 1, 2013 at 14:15

3 Answers 3

2

If you know both IDs, it's easy:

$myarray[2][32] == 'Anna'

If you know first one, you can use following trick:

array_shift(array_values($myarray[2])) == 'Anna'

If you know only later, it might be wise to flatten your array first:

$newarray = array()
foreach($myarray as $element) {
  $newarray += $element;
}
echo $newarray[32]; // Anna
Sign up to request clarification or add additional context in comments.

Comments

1

You should reconsider the structure.

If you'd like to retrieve 'Anna' if you have $id = 32:

$id = 32;
$name = null;
foreach ($myarray as $row) {
    if (isset($row[$id]) {
        $name = $row[$id];
        break;
    }
}

Comments

0

You can have your script assign the value of the two different IDs to $id1 and $id2 respectively, and then you can do this:

<?php 

$id1 = 0; //get your ID #1
$id2 = 53; //get your ID #2
echo $myarray[$id1][$id2]; //outputs Robert

?>

Hope this helps.

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.