Reputation: 1610
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!!
Upvotes: 0
Views: 152
Reputation: 1012
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;
}
}
Upvotes: 1
Reputation:
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.
Upvotes: 0
Reputation: 709
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
Upvotes: 2