medk
medk

Reputation: 9529

select data from a php multidimensional array

I have a multidimensional array as follows:

$a = array (
   #id           num  name      full name
    0 => array ( 65, 'name-1', 'Name One' ),
    1 => array ( 76, 'name-2', 'Name Two' ),
    2 => array ( 82, 'name-3', 'Name Three' )
);

Now, if I want to select 'name-1' (name) I use $a[0][1] and to select 'Name Three' (full name) I use $a[2][2].

So, I can select the number, the name or the full name if I have the id in the array.

But what if I have the number or the name and I want to select the full name? how could I get it?

Thanks.

Upvotes: 1

Views: 15354

Answers (3)

Shoe
Shoe

Reputation: 76240

If with id you mean the num:

$num = // num you want to find
foreach ($a as $b) {
    if ($b[0] == $num) {
        $name = $b[1];
        $full = $b[2];
        break;
    }
}

If with id you mean #ID then:

$id = // id you want to find
$num = $a[$id][0];
$name = $a[$id][1];
$full = $a[$id][2];

Upvotes: 3

Sietse
Sietse

Reputation: 717

You will have to loop through the array. For example, if you have the number:

$result = false;
foreach ($a as $value) {
    if ($value[0] == $number) { 
        $result = $value; break;
    }
}

Now you can use $value. To search by using the name or full name you have to use $value[1] and $value[2].

Upvotes: 1

MonkeyMonkey
MonkeyMonkey

Reputation: 836

you have the value and you want a key, so maybe you should think about restructuring your array. If you want to keep that structure, you need to iterate over each element (for, foreach), checking with array_search for your match (result is the array key or false).

for ($i = 0, $ix = count($a); $i < $ix; ++$i) {
  $pos = array_search($NAME, $a[$i]);
  if ($pos === false) {
    continue;
  }
  print_r($a[$i]);
  break;
}

Upvotes: 2

Related Questions