詳細検索

Eliminate nesting of associative arrays with only one element

Avatar
by maeno
2 min read

Eliminate nesting of associative arrays with only one element
Translated from 日本語 • View original

WordPress functions (especially in the $wpdb class, etc. When using the 'get_results()' method to get the value of the DB, etc.), and if the return value array has only one element but is an associative array, there are quite a few cases where nested loop processing is used when retrieving the value. It's been code-redundant and inefficient for a long time... I thought so, and this time I found a way to improve it, so I thought I'd leave it here as TIPS.

$array = array(
    array(
        'key_1' => 'value_1', 
        'key_2' => 'value_2', 
    ), 
);

foreach ($array as $nested_array) {
    foreach ($nested_array as $key => $value) {
        echo 'array["' . $key . '"] => "' . $value . '"<br />';
    }
}

Until now, I used to get the value by nesting the foreach loop like this (not useless, but not efficient) by nesting the associative array... So, can't we simply write processing by eliminating the nesting of this associative array and loop? I tried various PHP array functions. You can use functions that you don't use much, such as 'array_reduce()' or 'array_walk()', and you can build your own functions to eliminate nesting, but you have to prepare your own functions, which is not smart... I tried trial and error to see if I could solve it with just one line, and there was! You can get the leading element with 'array_shift()' and overwrite the original array variable.

$array = array_shift($array);

But if this is all there is to it, even one or more elements of the array will be overwritten, so I will put in the judgment of the number of elements.

$array = (count($array) == 1) ? array_shift($array) : $array;

When I rewrote the first code using this code,

$array = array(
    array(
        'key_1' => 'value_1', 
        'key_2' => 'value_2', 
    ), 
);

$array = (count($array) == 1) ? array_shift($array) : $array;
foreach ($array as $key => $value) {
    echo 'array["' . $key . '"] => "' . $value . '"<br />';
}

Well, it was much refreshing. My moyamoya also cleared up.

Related Articles