Uriahs Victor Uriahs Victor - 1 year ago 113
PHP Question

Pull out values from multidimensional associative array

I have a multidimensional array which Im trying to pull all the values of a certain key and assign it to a variable.

This is the array:

[I_would_not_know_the_name_of_this_key] => Array
[interval] => 3600
[display] => Once Hourly
[nor_this_one] => Array
[interval] => 43200
[display] => Twice Daily
[nor_this_one] => Array
[interval] => 86400
[display] => Once Daily

I want to always get the [display] value even when I do not know what the upper level value is.

function which contains the array above, more schedules can be added which is why I said I would not always know the top level key: https://codex.wordpress.org/Function_Reference/wp_get_schedules

My code so far:

$active_cron_schedules = wp_get_schedules(); //this is the
foreach ($active_cron_schedules as $key => $value) {
echo $key;


This outputs for example: 'I_would_not_know_the_name_of_this_key', 'nor_this_one', 'nor_this_one', I need to get in deeper.

Arrays have always given me a run for my money in PHP can't figure out how to loop through it :(

Thank you

Answer Source

I think what you are trying to do will be solved with a foreach() loop or array_column() depending on your version of php. The variable part is hard to answer because you have not given an example of what you would be doing with the variable. A common mistake is to overwrite the variable in a loop, but if all you want are all the display values (or any other key), try:

function getValByKey($array, $getKey = 'display')
        $new    =    array();
        foreach($array as $arr) {

            $new[]    =    $arr[$getKey];

        return $new;

$result    =    array(
                    'key1'=> array('interval'=>1,'display'=>'1d'),
                    'key2'=> array('interval'=>2,'display'=>'2d'),
                    'key3'=> array('interval'=>3,'display'=>'3d')
// To use
$display    =    getValByKey($result);

// Array column has the same basic function, but
// Only available in PHP 5 >= 5.5.0, PHP 7
$display    =    array_column($result,'display');


Both give you:

    [0] => 1d
    [1] => 2d
    [2] => 3d
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download