user1469270
user1469270

Reputation:

Create 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.

Upvotes: 1

Views: 514

Answers (3)

AbraCadaver
AbraCadaver

Reputation: 79024

Two good options:

If the todo_id is unique, let it be the key:

$js_arr[$row['todo_id']] = $row['todo_content'];

Or for a multi-dimensional array, needed if you have more than just todo_content:

$js_arr[] = array('todo_content' => $row['todo_content'], 'todo_id' => $row['todo_id']);

Upvotes: 1

Jon
Jon

Reputation: 437874

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.

Upvotes: 0

jeroen
jeroen

Reputation: 91792

I would use the ID as the key:

while($row = mysqli_fetch_array($r->query)){
    $js_arr[$row['todo_id']]['todo_content'] = $row['todo_content'];
}

Or - assuming you need everything that you get from the database:

while($row = mysqli_fetch_array($r->query)){
    $js_arr[$row['todo_id']] = $row;
}

What you can replace with (no loop, but no ID's as keys):

$js_arr = mysqli_fetch_all($r->query);

Upvotes: 0

Related Questions