tags:

views:

44

answers:

2

Hello,

I have been looking around for PHP tutorials and I found a very detailed one that have been useful to me.

But now, I have a question. The results showed by the API are stored into a $results array. This is the code (for instance):

$fetch = mysql_fetch_row($go);
$return = Array($fetch[0],$fetch[1]);    
$results = Array(  
    'news' => Array (  
        'id'    => $return[0],  
        'title' => $return[1]  
    )); 

My question is.. I want to display the last 10 news.. how do I do this? On normal PHP / mySQL it can be done as:

    while($var = mysql_fetch_array($table)) {
    echo "do something"
 }

How can I make it so the $results can print multiple results?

I have tried like:

while($var = mysql_fetch_array($table)) {
    $results = Array(  
        'news' => Array (  
            'id'    => $return[0],  
            'title' => $return[1]  
        )); 
 }

But this only shows me one result. If I change the $results .= Array(...) it gives error.

What can I do?

Thanks!

Edit

My function to read it doesn't read when I put it the suggested way:

function write(XMLWriter $xml, $data){
                            foreach($data as $key => $value){
                                    if(is_array($value)){
                                            $xml->startElement($key);
                                            write($xml, $value);
                                            $xml->endElement();
                                            continue;
                                    }
                                    $xml->writeElement($key, $value);
                            }
                    }
                    write($xml, $results);
A: 

Use [] to add elements to an array:

$results = array();

while($var = mysql_fetch_array($table)) {
    $results[] = Array(  
        'news' => Array (  
            'id'    => $var[0],  
            'title' => $var[1]  
        )); 
    }
}

You can then loop through the $results array. It's not an optimal structure but you should get the hang of it with this.

Tatu Ulmanen
The cool thing about using `$var[] =` is that it simply grabs the next highest key.
Marcus Adams
I think `$results[] = Array ( 'id' => $var[0], 'title' => $var[1]);` (or even `$results[$var[0]] = $var[1]`) would be more appropriate. Otherwise you create unnecessary nested arrays.
Felix Kling
A: 
$results[] = Array(  
        'news' => Array (  
            'id'    => $return[0],  
            'title' => $return[1]  
        )); 

That should do it.

If you are familiar with arrays, this is the equivalent of an array_push();

array_push() treats array as a stack, and pushes the passed variables onto the end of array. The length of array increases by the number of variables pushed. Has the same effect as:

<?php
$array[] = $var;
?>
Gazler