How to access the elements of a function's return array?

后端 未结 15 2045
栀梦
栀梦 2020-12-05 03:46

I need to return multiple values from a function, therefore I have added them to an array and returned the array.



        
相关标签:
15条回答
  • 2020-12-05 04:35
    $array  = data();
    
    print_r($array);
    
    0 讨论(0)
  • 2020-12-05 04:35

    here is the best way in a similar function

     function cart_stats($cart_id){
    
    $sql = "select sum(price) sum_bids, count(*) total_bids from carts_bids where cart_id = '$cart_id'";
    $rs = mysql_query($sql);
    $row = mysql_fetch_object($rs);
    $total_bids = $row->total_bids;
    $sum_bids = $row->sum_bids;
    $avarage = $sum_bids/$total_bids;
    
     $array["total_bids"] = "$total_bids";
     $array["avarage"] = " $avarage";
    
     return $array;
    }  
    

    and you get the array data like this

    $data = cart_stats($_GET['id']); 
    <?=$data['total_bids']?>
    
    0 讨论(0)
  • 2020-12-05 04:35

    In order to get the values of each variable, you need to treat the function as you would an array:

    function data() {
        $a = "abc";
        $b = "def";
        $c = "ghi";
        return array($a, $b, $c);
    }
    
    // Assign a variable to the array; 
    // I selected $dataArray (could be any name).
    
    $dataArray = data();
    list($a, $b, $c) = $dataArray;
    echo $a . " ". $b . " " . $c;
    
    //if you just need 1 variable out of 3;
    list(, $b, ) = $dataArray;
    echo $b;
    
    0 讨论(0)
提交回复
热议问题