Wednesday, 29 August 2018

Creating a multidimensional array from a loop in PHP

I'm trying to create a multidimensional array from some content I have in a database.
At the moment, I have this, which creates an array:
 $js_arr = [];
while($row = mysqli_fetch_array($r->query)){
    $js_arr[] = $row['todo_content'];
}

Returning:
Array ( [0] => first [1] => tester [2] => first item [3] => Hello!)
However, I also need to grab the $row['todo_id'].
I've tried this, but it only creates an array for the first row:
 $js_arr = [];
while($row = mysqli_fetch_array($r->query)){
    $js_arr['todo_content'] = $row['todo_content'];
    $js_arr['todo_id'] = $row['todo_id'];
}

Returning:
array(2) { ["todo_content"]=> string(3) "hey" ["todo_id"]=> string(2) "90" }

I'm still learning PHP so any help or pointers would be much appreciated.

Simply nest the items you want inside an array:
$js_arr[] = [
    'todo_content' => $row['todo_content'],
    'todo_id'      => $row['todo_id']
];

The $js_arr[] part cannot ever be anything else, because any other syntax will not unconditionally add an element to the end of your multidimensional array.

0 comments:

Post a Comment