I have an array in PHP as a result of the following query to a WordPress database:
SELECT * FROM wp_postmeta WHERE post_id = :id
I am returned a multidimensional array that looks like this:
Array ( [0] => Array ( [meta_id] => 380 [post_id] => 72 [meta_key] => _edit_last [meta_value] => 1 )
… etc.
What is the best way to find a particular key-value pair in this array?
For instance, how would I located the row where [meta_key]
= event_name so that I can extract that same row’s [meta_value]
value into a PHP variable?
I realize I could turn this into many individual MySQL queries. Does anyone have an opinion of the efficiency of doing 10 SQL queries in a row rather than searching the array 10 times? I would think since the array is in memory, that will be the fastest method to find the values I need.
Alternatively, is there a better way to query the database from the beginning so that my result set is formatted in a way that is easier to search?
Lets assume that you always want to search for the columns “meta_key” creating the array you could do something like this:
Then you will have a associative array the the value of “meta_key” as the primary index. But in this case the “meta_key” has to be unique as otherwise you would overwrite the values.
Your example would than look like this:
And you can easily get the “meta_value” by using the index:
Is that what you wanted to have?
EDIT: If you have mor than one value per “meta_key” you could also create a multidimensional array for each key. Just use this line within the while loop instead:
You will than have an array for each row per “meta_value” so your array might look like this:
You can then use another loop to get all values from a group of “meta_key” values.
Based on the array you gave, do the following: