8

I've a 2-dimensional array and i want to push values to it with a while loop like;

$arr[0][1] = 1. value
$arr[0][2] = 2. value

I've tried

while ($zRow = mysql_fetch_array($zQuery))
{
    $props[]['name'] = $zRow['name'];
    $props[]['photo'] = $zRow['thumbnail'];
}

This loop pushes name to $props[0][name] and thumbnail to $props[1][photo]

I also tried

$j = 0;
while($zRow = mysql_fetch_array($zQuery))
{
    $props[$j]['name'] =$zRow['name'];
    $props[$j]['photo'] =$zRow['thumbnail'];
    $j += 1;
}

That works but with this I when I use foreach loop later, it makes trouble like "Illegal offset type".

Here is my foreach loop:

foreach ($props as $no)
{
    echo $props[$no]['name'];
} 

Now my questions:

  1. Are there any other way than while loop with $j variable like array_push() for 2-dimensional arrays?
  2. How can I use foreach loop for 2-dimensional arrays?

2 Answers 2

18

You could change the first loop to the following:

while($zRow = mysql_fetch_array($zQuery))
{
    $row = array();
    $row['name'] = $zRow['name'];
    $row['photo'] = $zRow['thumbnail'];
    $props[] = $row;
}

Your method also works, but you need that extra variable.

In your second loop, what you actually need to be doing is:

foreach($props as $index => $array)
{
    echo $props[$index]['name'];
    // OR
    echo $array['name'];
}
Sign up to request clarification or add additional context in comments.

Comments

4

Pushing anything onto an array with $myArray[] = 'foo' will increment the array's counter.

For multidimensional array, you need to populate the "inner" array, then push it to the "outer" (in your case $props) array.

while($zRow = mysql_fetch_array($zQuery)) {
    $data = array('name' => $zRow['name'], 'photo' => $zRow['thumbnail']);
    $props[] = $data;
}

To iterate over multidimensional arrays whose depth is known:

foreach ($props as $prop) {
    foreach ($prop as $key => $value) {
        echo "{$key} => {$value}" . PHP_EOL;
    }
}

If the depth of the nesting is not known, you may have to use a recursive function to gather the data.

1 Comment

and how can i use foreach for 2-dimensional arrays?

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.