How to combine multiple arrays that share a common value

Viewed 57

I am creating a web page that will allow comparisons of MySQL global variables for two or more instances. The user will select the instance's and a php function with use mysqli to get the results. The results will come in the below format:

Array (
    [0] => Array ( [VARIABLE_NAME] => activate_all_roles_on_login [host1:3306] => OFF )
    [1] => Array ( [VARIABLE_NAME] => admin_address [host1:3306] => 0.0.0.1 )
)
Array ( 
    [0] => Array ( [VARIABLE_NAME] => activate_all_roles_on_login [host1:3307] => OFF )
    [1] => Array ( [VARIABLE_NAME] => admin_address [host1:3307] => 0.0.0.1 )
)
Array ( 
    [0] => Array ( [VARIABLE_NAME] => activate_all_roles_on_login [host3:3308] => OFF )
    [1] => Array ( [VARIABLE_NAME] => admin_address [host3:3308] => 0.0.0.2 )
)

I am wanting to combine these on the variable name value, like below:

[0] => Array ( [VARIABLE_NAME] => activate_all_roles_on_login [host1:3306] => OFF [host1:3307] => OFF [host3:3308] => OFF )

I've tried using array_combine, but that only made more of a mess.

The end goal of this is to make an array that can be easily turned into a table like below:

end goal

2 Answers

I would recommend you to try to implement it with pure SQL, however if you must to do it with PHP, here are some solutions.

Your array:

$queryResult = [
    [
        ['VARIABLE_NAME' => 'activate_all_roles_on_login', 'host1:3306' => 'OFF'] ,
        ['VARIABLE_NAME' => 'admin_address', 'host1:3306' => '0.0.0.1'] ,
    ],
    [
        ['VARIABLE_NAME' => 'activate_all_roles_on_login', 'host1:3307' => 'OFF'],
        ['VARIABLE_NAME' => 'admin_address', 'host1:3307' => '0.0.0.2'] ,
    ],
    [
        ['VARIABLE_NAME' => 'activate_all_roles_on_login', 'host1:3308' => 'OFF'] ,
        ['VARIABLE_NAME' => 'admin_address', 'host1:3308' => '0.0.0.3'] ,
    ]
];

If you are sure that 'activate_all_roles_on_login' would always be on the first place in result, your task can be done in one line:

var_dump(array_merge(...array_column($queryResult, 0)));

However, if your query result may vary, you can try something like this:

$result = [];
foreach ($queryResult as $row) {
    $subresult = array_column($row, null, 'VARIABLE_NAME');
    if (isset($subresult['activate_all_roles_on_login'])) {
        $result[] = $subresult['activate_all_roles_on_login'];
    }
}

var_dump(array_merge(...$result));

Edit:

Also it can be done with two loops (which is kind of slower I guess):

foreach ($queryResult as $row) {
    foreach ($row as $entry) {
        if (isset($entry['VARIABLE_NAME']) && $entry['VARIABLE_NAME'] === 'activate_all_roles_on_login') {
            $result[] = $entry;
        }
    }
}

var_dump(array_merge(...$result));
Related