Search code examples
phparraysforeachpush

Populate an array containing two-element rows while looping over a mysql query resultset


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?

Solution

  • 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'];
    }