简体   繁体   中英

How do I add an array to a multidimensional array?

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
//      )

}

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
    )

}

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);

使用php的方法:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM