cattarantadoughan
cattarantadoughan

Reputation: 509

Accessing associative array element using another element in PHP

I'm quite new to PHP and I'm not really sure how to ask this question. My data is like this (displayed in JSON for easy viewing but i actually use array)

[{"_id":"1","title":"Month & Year","description":"To be used in Jurisprudence"},
 {"_id":"3","title":"Bible Version I","description":"Testament - Book - Chapter"}]

I know in PHP that i can access elements of associative array by using foreach as well as using the standard for loop.

e.g:

for($n=0;$n<sizeof($array_data);$n++){
     echo $array_data[$n]['title'];
}

Instead of using the index, what i want to do if possible is to access title using the _id. Something like, if have 3 as _id it should display the corresponding title in that array which is Bible Version I.

Upvotes: 1

Views: 80

Answers (2)

Fawaz
Fawaz

Reputation: 3560

A more efficient solution without a loop would be to use array_search with array_column :

$key = array_search("3", array_column($array_data, '_id'));
if ($myArray[$key]) {
  echo $myArray[$key]['_id'] . ' : ' . $myArray[$key]['title'];
}

Uses php 5.5.0 or above. Refer here

Upvotes: 1

Barmar
Barmar

Reputation: 780723

Use an if statement.

foreach ($array_data as $item) {
    if ($item['_id'] == 3) {
        echo $item['title'];
        break;
    }
}

If you'll be doing this a lot, you should probably change your array to an associative array, so you can then just use $array_data[3]. E.g. it should be:

{
    "1": {"_id":"1","title":"Month & Year","description":"To be used in Jurisprudence"},
    "3": {"_id":"3","title":"Bible Version I","description":"Testament - Book - Chapter"}
}

Upvotes: 2

Related Questions