0

How do I append arrays to a multidimensional array? When it goes through the loop, it needs to add the data as an array to create multiple arrays. It encodes to json and sends to an Android phone.

Relevant code:

$data = array(
    "articles" => array(
        array(
            'id'=> "4335",
            'cat'=> "Lifestyle",
            'title'=> "Welcome to field and rural life",
            'url'=> "http://www.fieldandrurallife.com"

        ),
        array(
            'id'=> "4336",
            'cat'=> "Lifestyle",
            'title'=> "Thank You",
            'url'=> "www.thankyou.com"

        )
    )
);

while($row = mysql_fetch_array($sql))
{
    $id = $row["id"]; 
    $cat = $row["category"];
    $title = $row["title"];  
    $url = $row["url"];

    // HOW DO I ADD THIS INTO THE ARTICLES ARRAY??
//    array(
//       'id'=> $id,
//        'cat'=> $cat,
//        'title'=> $title,
//        'url'=> $url
//      )

}
1
  • 4
    $data['articles'][] = array('id'=> $id, 'cat'=> $cat, 'title'=> $title, 'url'=> $url); Commented Jul 9, 2013 at 13:57

3 Answers 3

2

Simply:

while($row = mysql_fetch_array($sql)){
    $id = $row["id"]; 
    $cat = $row["category"];
    $title = $row["title"];  
    $url = $row["url"];

    $data['articles'][] = array(
                          'id'=> $id,
                          'cat'=> $cat,
                          'title'=> $title,
                          'url'=> $url
    )

}
Sign up to request clarification or add additional context in comments.

Comments

1

Try using array_push with json_encode

When you pull from the database, if you only pull the columns you need, then just push the row directly onto the array, since it's already an array.

while($row = mysql_fetch_array($sql))
{
    // Add your new array to the array
    array_push($data['articles'], $row);
}

// Then you can encode your array to JSON like so.
$json_version = json_encode($data);

Comments

0

Use php's method:

array_push($data["article"], $row);

Comments

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.