1

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.

3 Answers 3

3

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];
Sign up to request clarification or add additional context in comments.

1 Comment

A break would probably make that for loop more efficient.
2

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;
}

Comments

1

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].

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.