简体   繁体   中英

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.

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

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

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.

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