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.

3
  • 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. Commented Sep 30, 2011 at 22:38
  • This was already answered here stackoverflow.com/questions/2121548/… Commented Sep 30, 2011 at 22:40
  • @Mark sorry - I did look but didn't find that post Commented Sep 30, 2011 at 22:41

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

thank you very much - I can't believe I didn't think of that!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.