1

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.

3 Answers 3

1

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']);
Sign up to request clarification or add additional context in comments.

2 Comments

Would there be any advantages or disadvantages with using the todo_id as the key? (I'm js encoding this for jQuery)
If you need to access a row and know the id it would be easier to access that row: js: value = js_arr[5]["todo_content"] php: $value = $js_arr[5]["todo_content"]
0

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.

2 Comments

Thanks, I figured this also works: $js_arr[$i]['todo_content'] = $row['todo_content']; Could you elaborate on the "not be anything else" part?
@tmyie: Another way to say "obviously you have to leave that alone, the solution will be elsewhere".
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.