簡體   English   中英

以數組形式返回php for-each輸出

[英]Return php for-each output as an array

對於給定的foreach循環,使用echo顯示輸出

$output = array();
$counts = array('45','55','75','95');

foreach ($counts as $count) {
    $output= $count + 10 ;
    echo $output
}

它給

output : 556585105

但是我不想打印此內容,而是將$output存儲為數組變量。

我想在哪里獲得$output = array('55','65', '85', '105'); 因此,以后我可以使用鍵值從$output獲取任何值。

您可以修改原始數組,例如:

$counts = array('45','55','75','95');
foreach ($counts as &$count) {
    $count += 10;
}
print_r($counts);

演示

您需要更改分配。 您正在做的是覆蓋$ output。 因此$ output包含最后一個賦值。

$output = array();
$counts = array('45','55','75','95');

foreach ($counts as $count) {

    $output[] = $count + 10 ; // change this        
}

嘗試這個,

<?php

$output = array();
$counts = array('45','55','75','95');

foreach ($counts as $count) {   
    $output[] = $count + 10 ;
    print_r($output);
}
?>

你的錯誤是,你沒有$output =當你不得不做$output[] = 還要記住,您不能像這樣echo變量,但是可以使用print_rvar_dump

您可以執行以下操作:

   $array = array();
   $counts = array('45','55','75','95');

   foreach ($counts as $count) {
        $array[] = $count + 10 ;        
   }
   print_r($array); // here is your array

您可以使用此array_push()函數

<?php
$output = array();
$counts = array('45','55','75','95');
foreach ($counts as $count) {
array_push($output,$count + 10 );
}
print_r($output);
?>

array_push()函數是php的內置函數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM