-1

I've looked on the web but all I can find is how to echo data from arrays, but I need to add to them. This array is multidimensional so I need to add an array to an array all the time. How do I do this?

Heres the code:

<?php 
$data = array(
    "contacts" => array(
        array(
            'id'=> "1",
            'catagory'=> "LifeStyle",
            'title'=> "Some Cool Title",
            'url'=> "http://example.com",
        ),
    )
);

$sql = mysql_query("SELECT * FROM magazines WHERE category = '$cat'");
while($row = mysql_fetch_array($sql)){
    $id = $row["id"]; 
    $cat = $row["category"];
    $title = $row["title"];  
    $url = $row["url"];

    // add to array 
//  array(
//      'id'=> "$id",
//      'catagory'=> "$cat",
//      'title'=> "$title",
//      'url'=> "$url",
//  ),  
}
mysql_close();
echo json_encode($data);
?>
1
  • 1
    $data['contacts'][] = $row is all you need. Commented Jun 22, 2013 at 21:36

2 Answers 2

1

Just do this...

while($row = mysql_fetch_array($sql)){

 $data['contacts'][] = $row;
}

Or this...

while($row = mysql_fetch_array($sql)){
 array_push($data['contacts'], $row);
}

Then a print_r will show you your array...

print_r($data);
Sign up to request clarification or add additional context in comments.

Comments

1

Instead of doing SELECT * select only the fields you want to push into the array. Something like this

<?php
    $sql = mysql_query("SELECT id, category, title, url FROM magazines WHERE category = '$cat'");
    while($row = mysql_fetch_array($sql)){
        $data['contacts'][] = $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.