【问题标题】:How to access the elements of a function's return array?如何访问函数返回数组的元素?
【发布时间】:2011-08-07 05:55:05
【问题描述】:

我需要从一个函数中返回多个值,因此我将它们添加到一个数组并返回该数组。

<?
function data(){
    $a = "abc";
    $b = "def";
    $c = "ghi";

    return array($a, $b, $c);
}
?>

如何通过调用上述函数接收$a$b$c的值?

【问题讨论】:

标签: php arrays function


【解决方案1】:

您可以将数组键添加到返回值中,然后使用这些键来打印数组值,如下所示:

function data() {
    $out['a'] = "abc";
    $out['b'] = "def";
    $out['c'] = "ghi";
    return $out;
}

$data = data();
echo $data['a'];
echo $data['b'];
echo $data['c'];

【讨论】:

    【解决方案2】:

    你可以这样做:

    list($a, $b, $c) = data();
    
    print "$a $b $c"; // "abc def ghi"
    

    【讨论】:

    • @GiacomoTecyaPigani 列表不是函数,它是docs 中所述的语言结构。
    • 对于习惯了 Python 的元组解包或 C++17 的结构化绑定的人来说,这是迄今为止返回多个值最自然的方式。
    • 甜蜜又简单
    • 从 PHP 7.1 开始,可以使用 [$a, $b, $c] = data();
    【解决方案3】:
    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

    【讨论】:

    【解决方案4】:

    数据函数返回一个数组,因此您可以像访问数组元素一样访问函数的结果:

    <?php
    ...
    $result = data();
    
    $a = $result[0];
    $b = $result[1];
    $c = $result[2];
    

    或者您可以使用list() 函数,正如@fredrik 建议的那样,在一行中执行相同的操作。

    【讨论】:

      【解决方案5】:
      $array  = data();
      
      print_r($array);
      

      【讨论】:

        【解决方案6】:

        从 PHP 5.4 开始,您可以利用数组取消引用并执行以下操作:

        <?
        
        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"
        ?>
        

        【讨论】:

        • 警告:您可能不想对函数进行 3 次评估!
        【解决方案7】:
        <?php
        function demo($val,$val1){
            return $arr=array("value"=>$val,"value1"=>$val1);
        
        }
        $arr_rec=demo(25,30);
        echo $arr_rec["value"];
        echo $arr_rec["value1"];
        ?>
        

        【讨论】:

          【解决方案8】:

          为了获取每个变量的值,您需要将函数视为数组:

          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;
          

          【讨论】:

            【解决方案9】:

            也许这就是您搜索的内容:

            function data() {
                // your code
                return $array; 
            }
            $var = data(); 
            foreach($var as $value) {
                echo $value; 
            }
            

            【讨论】:

              【解决方案10】:

              这是类似功能中最好的方法

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

              你得到这样的数组数据

              $data = cart_stats($_GET['id']); 
              <?=$data['total_bids']?>
              

              【讨论】:

                【解决方案11】:

                我认为最好的方法是创建一个全局 var 数组。然后通过将其作为引用传递,在函数数据中做任何你想做的事情。也不需要退货。

                $array = array("white", "black", "yellow");
                echo $array[0]; //this echo white
                data($array);
                
                function data(&$passArray){ //<<notice &
                    $passArray[0] = "orange"; 
                }
                echo $array[0]; //this now echo orange
                

                【讨论】:

                  【解决方案12】:

                  这是我在 yii 框架中所做的:

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

                  然后在我的视图文件中:

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

                  我正在做的事情是抓住我选择的桌子的一个 cretin 部分。应该只适用于 php 减去 db 的“Yii”方式

                  【讨论】:

                    【解决方案13】:

                    正如 Felix Kling 在第一个响应中指出的那样,根本问题围绕着访问数组中的数据。

                    在下面的代码中,我使用 print 和 echo 结构访问了数组的值。

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

                    【讨论】:

                      【解决方案14】:

                      我一直在寻找一种比我现在使用的更简单的方法,但在这篇文章中没有回答。但是,我的方法有效,我没有使用上述任何方法:

                      function MyFunction() {
                        $lookyHere = array(
                          'value1' => array('valuehere'),
                          'entry2' => array('valuehere')
                        );
                        return $lookyHere;
                      }
                      

                      我的功能没有问题。我循环读取数据以显示我的关联数据。我不知道为什么有人会建议上述方法。如果您希望在一个文件中存储多个数组但没有加载所有数组,请使用我上面的函数方法。否则,所有数组都将加载到页面上,从而降低您的网站速度。我想出了这段代码来将我所有的数组存储在一个文件中,并在需要时使用单独的数组。

                      【讨论】:

                      • 为什么要声明一个一次性变量。我不会使用这个答案。您的样本与 OP 的数据不同。有充分的理由不声明关联数组,但标准很大程度上取决于将要对返回的数据做什么。顺便说一句,您的函数确实加载/填充所有数组。
                      【解决方案15】:

                      你的功能是:

                      function data(){
                      
                      $a = "abc";
                      $b = "def";
                      $c = "ghi";
                      
                      return array($a, $b, $c);
                      }
                      

                      它返回一个数组,其中位置 0 是 $a,位置 1 是 $b,位置 2 是 $c。因此,您可以通过这样做来访问 $a:

                      数据()[0]

                      如果您执行 $myvar = data()[0] 并打印 $myvar,您将得到“abc”,这是函数内部分配给 $a 的值。

                      【讨论】:

                        猜你喜欢
                        • 2011-04-08
                        • 2023-04-03
                        • 2012-06-05
                        • 2018-04-22
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 2013-06-12
                        相关资源
                        最近更新 更多