programing

함수에서 반환된 어레이의 요소에 액세스하는 방법

sourcejob 2022. 10. 15. 09:56
반응형

함수에서 반환된 어레이의 요소에 액세스하는 방법

함수에서 여러 값을 반환해야 하기 때문에 이를 어레이에 추가하고 어레이를 반환했습니다.

<?

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에서 권장하는 대로 동일한 작업을 한 줄로 수행할 수 있습니다.

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

각 변수의 값을 가져오려면 함수를 배열과 동일하게 처리해야 합니다.

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;

//Important not to forget the commas in the list(, $b,).

검색한 내용은 다음과 같습니다.

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

여기 유사한 기능에서 가장 좋은 방법이 있다

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

위의 모든 것은 코멘트에서 언급한 바와 같이 PHP 7.1 이후 오래된 것 같습니다.

python에서처럼 배열에서 반환되는 값에 쉽게 액세스할 수 있는 방법을 찾는 경우 다음 구문을 사용합니다.

[$a, $b, $c] = data();

가장 좋은 방법은 글로벌 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

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

내가 선택한 테이블의 빈자리를 잡고 있는 것.php에서 DB의 "Yii" 방식을 뺀 경우만 작동합니다.

Felix Kling이 첫 번째 응답에서 지적했듯이 근본적인 문제는 어레이 내의 데이터에 액세스하는 데 있습니다.

다음 코드에서는 프린트 및 에코 구조를 사용하여 어레이의 값에 액세스했습니다.

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

지금보다 쉬운 방법을 찾고 있었는데 이 게시물에는 답이 없네요.그러나 내 방법은 작동하며 앞서 말한 방법을 사용하지 않습니다.

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

기능에는 문제가 없습니다.관련 데이터를 표시하기 위해 루프에서 데이터를 읽습니다.왜 누군가가 위와 같은 방법을 제안하는지 모르겠다.여러 어레이를 하나의 파일에 저장하지만 모든 어레이가 로드되지 않은 경우 위의 기능 방법을 사용하십시오.그렇지 않으면 모든 어레이가 페이지에 로드되어 사이트 속도가 느려집니다.이 코드는 모든 어레이를 하나의 파일에 저장하고 필요에 따라 개별 어레이를 사용하기 위해 고안되었습니다.

기능은 다음과 같습니다.

function data(){

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

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

위치 0이 $a, 위치 1이 $b, 위치 2가 $c인 배열을 반환합니다.따라서 다음과 같이 $a에 액세스할 수 있습니다.

data()[0]

$myvar = data() [0]를 실행하고 $myvar를 인쇄하면 함수 내의 $a에 할당된 값인 "sys"가 표시됩니다.

언급URL : https://stackoverflow.com/questions/5692568/how-to-access-elements-in-an-array-returned-from-a-function

반응형