How do I efficiently locate key-value pairs in a multi-dimensional PHP array?

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:

Read More
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?

Related posts

Leave a Reply

2 comments

  1. Lets assume that you always want to search for the columns “meta_key” creating the array you could do something like this:

    $arr = array();
    while($row = $mysqli->fetch_assoc()){
        $arr[$row['meta_key']] = $row;
    }
    

    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:

    Array ( [_edit_last] => Array ( [meta_id] => 380, [post_id] => 72, [meta_key] => _edit_last, [meta_value] => 1 )
    

    And you can easily get the “meta_value” by using the index:

    $var = $arr['_edit_last']['meta_value'];
    

    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:

    $arr[$row['meta_key']][] = $row;
    

    You will than have an array for each row per “meta_value” so your array might look like this:

    Array ( [_edit_last] => Array ( [0] => Array( [meta_id] => 380, [post_id] => 72, [meta_key] => _edit_last, [meta_value] => 1 ) )
    

    You can then use another loop to get all values from a group of “meta_key” values.

  2. Based on the array you gave, do the following:

    $multiArray = Array ( [0] => Array ( ['meta_id'] => 380, ['post_id'] => 72, ['meta_key'] => _edit_last, ['meta_value'] => 1 );
    $needleKey = 'meta_key';
    $needle = 'event_name';
    
    foreach ($multiArray as $key => $data) {
        if ($data[$needleKey] == $needle) {
            echo $key;
            break;
        }
    }