medk
medk

Reputation: 9529

Get key of element which has a specified value

Is there a way to access a multidimensional array from any position? example:

$arr = array (

    1 => array ( 1, 'some-url-one', 'Some Title One' ),

    2 => array ( 2, 'some-url-two', 'Some Title Two' ),

    3 => array ( 2, 'some-url-three', 'Some Title Three' ),

);

Then, if we have the id of an item, for example 2 and want to get the title of that item we simply use:

$title = $arr[2][2]; // which outputs Some Title Two

And if we want to get the url of that same item we simply use:

$title = $arr[2][1];  // which outputs some-url-two

BUT what if we have the URL (some-url-two) and want to get the id or title of that item?

There are 2 obligations:

1- loop through the array and check if that URL exists 2- get the id and the title

How to do that the best way? I already have 3 arrays:

1- id to url

2- url to id

3- id to title

$id2url = array (

    1 => 'some-url-one',
    2 => 'some-url-two',
    3 => 'some-url-three'

);

And the two others are the same procedure. So I wanted to optimize my code by combining the 3 arrays. so how to access the id and the title with a given url?

Upvotes: 3

Views: 515

Answers (3)

Patrick
Patrick

Reputation: 3450

There is an easier way to handle this I think. If you already have the URL then you could potentially already have the index in the parent array of all the data. In which case you could simply access it with this

$found_id = $arr[$known_parent_idx][0];
$found_title = $arr[$known_parent_idx][2];

However if you don't have that index then you can do a loop-based check like so. Say your looping through this multidimensional array, here is how this works.

foreach ($arr AS $idx => $subarr)
{
  if ($subarr[1] == $known_url)
  {
    $found_id = $subarr[0];
    $found_title = $subarr[2];
  }
}

Now you can make this even easier for you if the URL is also the parent index. In this case we are talking about an associative array. Here is a structure that could be more helpful.

$arr = array (
  'some-url-one' => array ( 'id' => 1, 'title' => 'Some Title One' ),
  'some-url-two' => array ( 'id' => 2, 'title' => 'Some Title Two' ),
  'some-url-three' => array ( 'id' => 2, 'title' => 'Some Title Three' ),
);

This would allow you to instantly find what your looking for without any searching at all. But this would require that the URLs be unique in each case.

Upvotes: 0

hakre
hakre

Reputation: 197609

You might look for array_flip() PHP Manual, it will make your lookup arrays work with their values as keys:

$id2url = array (

    1 => 'some-url-one',
    2 => 'some-url-two',
    3 => 'some-url-three'

);

$url2id = array_flip($id2url); // keys will become values, and values keys.

$id = $url2id[$url];

$title = $arr[$id][2];

Upvotes: 2

qbert220
qbert220

Reputation: 11556

You can use array_search like this:

$id = array_search($url, $url2id);

Upvotes: 1

Related Questions