0

Let's say I have the following table in my database:

Name        | Description      | Image

App         | Some description | somefile.png
Another App | Another descript | anotherfile.png

What I want to do is create a JSON array like this:

{
    "App": {
        "name": "App",
        "description": "Some description",
        "Image": "somefile.png"
    },
    "Another App": {
        "name": "Another App",
        "description": "Another descript",
        "Image": "anotherfile.png"
    }
}

What I'm struggling with is pushing the key>value pair on. I can push just the value, with a non-keyed array, but I cannot push the key>value pair onto my array.

What I've tried:

$res = mysql_query('SELECT * FROM `apps`;');
if ($res) {
    $temp = array();
    while ($row = mysql_fetch_array($res)) {
        $name = $row['name'];
        $descript = $row['description'];
        $img = $row['image'];
        $new = array('name'=>$name,'description'=>$descript,'img'=>$img);
        array_push($temp,$new); // how do I make this push with a key?
    }
}
echo json_encode($temp);

My problem is with the array_push() function - I want it to push with the name as the key but I can't get it to.

Alex Coplan
  • 13,211
  • 19
  • 77
  • 138
  • 1
    `array_push()` will create a stack, not an associative array, which means it's not what you want. Just use a keyed value and set it to your keyed/associative array. – Jared Farrish Sep 30 '11 at 22:38
  • This was already answered here http://stackoverflow.com/questions/2121548/how-to-push-both-value-and-key-into-array-with-php – Mark Sep 30 '11 at 22:40
  • @Mark sorry - I did look but didn't find that post – Alex Coplan Sep 30 '11 at 22:41

1 Answers1

2

Try this:

while ($row = mysql_fetch_array($res)) {
    $name     = $row['name'];
    $descript = $row['description'];
    $img      = $row['image'];

    $temp[$name] = array('name'=>$name,'description'=>$descript,'img'=>$img);
}
drew010
  • 68,777
  • 11
  • 134
  • 162