Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Trying to build the multidimensional array with a foreach using record from a db...

enter image description here

$servDetails = array(
    // CSS Servers
    'css' => array(
        'server1' => array(
            'id' => 'id1',
            'type' => 'css',
            'host' => 'ip:port'
        ),
        'server2' => array(
            'id' => 'id2',
            'type' => 'css',
            'host' => 'ip:port'
        )
    )
);

What's the best way of doing this?

share|improve this question
3  
Use a loop. This is pretty straight forward. –  John Conde Jan 14 at 20:26
add comment

closed as unclear what you're asking by John Conde, Dagon, Tomasz Kowalczyk, Michael Berkowski, BeatAlex Mar 17 at 14:27

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question.If this question can be reworded to fit the rules in the help center, please edit the question.

1 Answer

up vote 1 down vote accepted

Assuming you have executed and have populated an associative array:

// create your containing array
$servDetails = array('css' => array());

// iterate over the results
foreach ($results as $result) {
    $servDetails['css'][$result['server_name']] = array(
        'id' => $result['server_id'],
        'type' => 'css',
        'host' => $result['server_ip'] . ':' . $result['server_port']
    );
}

I'm not sure where the 'css' portion comes from in your sample, so you may have to adjust this to make it dynamic (if it is in fact dynamic).

You could also build this array structure directly when pulling the results from the db:

if ($results = $mysqli->query($query)) {
    while ($result = $results->fetch_assoc()) {
        $servDetails['css'][$result['server_name']] = array(
            'id' => $result['server_id'],
            'type' => 'css',
            'host' => $result['server_ip'] . ':' . $result['server_port']
        );
    }
share|improve this answer
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.