IT박스

PHP 함수 반환 배열

itboxs 2020. 10. 31. 09:29

PHP 함수 반환 배열


함수에서 여러 값을 반환해야하므로 배열에 추가하고 배열을 반환했습니다.

<?

function data(){

$a = "abc";
$b = "def";
$c = "ghi";

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


?>

어떻게 값을받을 수 있습니다 $a, $b, $c위의 함수를 호출하여?


다음과 같이 반환 값에 배열 키를 추가 한 다음 이러한 키를 사용하여 배열 값을 인쇄 할 수 있습니다.

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

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

다음과 같이 할 수 있습니다.

list($a, $b, $c) = data();

print "$a $b $c"; // "abc def ghi"

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


데이터 함수는 배열을 반환하므로 일반적으로 배열의 요소에 액세스하는 것과 동일한 방식으로 함수의 결과에 액세스 할 수 있습니다.

<?php
...
$result = data();

$a = $result[0];
$b = $result[1];
$c = $result[2];

또는 list()@fredrik이 권장하는대로 함수를 사용하여 한 줄에서 동일한 작업을 수행 할 수 있습니다 .


$array  = data();

print_r($array);

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

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

비슷한 기능에서 가장 좋은 방법이 있습니다.

 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']?>

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;

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


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

$data = data(); 
$a = $data[0];
$b = $data[1];
$c = $data[2];

I think the best way to do it is to create a global var array. Then do whatever you want to it inside the function data by passing it as a reference. No need to return anything too.

$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

Maybe this is what you searched for :

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

참고URL : https://stackoverflow.com/questions/5692568/php-function-return-array