1

I making a script to display data from some VPSs, which is being stored in a MySQL database.

$result = mysql_query("SELECT * FROM data");
$data = array();
while ($row = mysql_fetch_array($result)) {
    $data[] = array(
             'id' => $row['id'],
             'hostname' => $row['hostname'],
             'loadavrg' => $row['load average']
    );
}

I would like to separate data by hostnames so I can read it like the following example:

foreach ($data['sitename.com'] as $d)
    echo $d['loadavrg'];

I already tried with the following code (just for testing), but didn't work:

$result = mysql_query("SELECT * FROM data WHERE hostname='sitename.com'");
$data = array();
while ($row = mysql_fetch_array($result)) {
    $data[] = array(
        'sitename.com' => array(
            'id' => $row['id'],
            'loadavrg' => $row['load average']
        )
    );
}

I'm just missing the right way and syntax to achieve it.

0

2 Answers 2

3

Every element should be added as subarray of 'sitename.com':

while ($row = mysql_fetch_array($result)) {
    $data['sitename.com'][] = array(
        'id' => $row['id'],
        'loadavrg' => $row['load average']
    );
}
Sign up to request clarification or add additional context in comments.

1 Comment

Uh, I though that I already tried that, I must have forgot the second brakets after ['sitename']... however, it works! thanks :)
2

Try this,

while ($row = mysql_fetch_array($result)) {
    $hostname = $row['hostname'];
    $data[$hostname][] = array(
        'id' => $row['id'],
        'loadavrg' => $row['load average']
    );
}

3 Comments

What if sitename.com has multiple entries?
@SougataBose I guess the edit would handle the exact requirement
Yea, that's help even more that I was asking for, thanks, but you miss [] after [$hostname] if I ain't wrong, that's what I already tried and didn't worked because I was missing it too.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.