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

后端 未结 15 2046
栀梦
栀梦 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:19

    From PHP 5.4 you can take advantage of array dereferencing and do something like this:

    <?
    
    function data()
    {
        $retr_arr["a"] = "abc";
        $retr_arr["b"] = "def";
        $retr_arr["c"] = "ghi";
    
        return $retr_arr;
    }
    
    $a = data()["a"];    //$a = "abc"
    $b = data()["b"];    //$b = "def"
    $c = data()["c"];    //$c = "ghi"
    ?>
    
    0 讨论(0)
  • 2020-12-05 04:20

    The underlying problem revolves around accessing the data within the array, as Felix Kling points out in the first response.

    In the following code, I've accessed the values of the array with the print and echo constructs.

    function data()
    {
    
        $a = "abc";
        $b = "def";
        $c = "ghi";
    
        $array = array($a, $b, $c);
    
        print_r($array);//outputs the key/value pair
    
        echo "<br>";
    
        echo $array[0].$array[1].$array[2];//outputs a concatenation of the values
    
    }
    
    data();
    
    0 讨论(0)
  • 2020-12-05 04:22

    You can add array keys to your return values and then use these keys to print the array values, as shown here:

    function data() {
        $out['a'] = "abc";
        $out['b'] = "def";
        $out['c'] = "ghi";
        return $out;
    }
    
    $data = data();
    echo $data['a'];
    echo $data['b'];
    echo $data['c'];
    
    0 讨论(0)
  • 2020-12-05 04:22

    This is what I did inside the yii framewok:

    public function servicesQuery($section){
            $data = Yii::app()->db->createCommand()
                    ->select('*')
                    ->from('services')
                    ->where("section='$section'")
                    ->queryAll();   
            return $data;
        }
    

    then inside my view file:

          <?php $consultation = $this->servicesQuery("consultation"); ?> ?>
          <?php foreach($consultation as $consul): ?>
                 <span class="text-1"><?php echo $consul['content']; ?></span>
           <?php endforeach;?>
    

    What I am doing grabbing a cretin part of the table i have selected. should work for just php minus the "Yii" way for the db

    0 讨论(0)
  • 2020-12-05 04:25

    you can do this:

    list($a, $b, $c) = data();
    
    print "$a $b $c"; // "abc def ghi"
    
    0 讨论(0)
  • 2020-12-05 04:26
    function give_array(){
    
        $a = "abc";
        $b = "def";
        $c = "ghi";
    
        return compact('a','b','c');
    }
    
    
    $my_array = give_array();
    

    http://php.net/manual/en/function.compact.php

    0 讨论(0)
提交回复
热议问题