开发者

PHP Api - Results/Array question

开发者 https://www.devze.com 2023-01-20 04:22 出处:网络
I have been looking around for PHP tutorials and I found a very detailed one that have been useful to me.

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


$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;
?>


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消