PHP之數組foreach,join

來源:互聯網
上載者:User
一,foreach的使用
例如:$arr = array("one", "two", "three");
reset($arr);//把數組的內部指標指向第一個元素,並返回這個元素的值。若失敗,則返回 FALSE。

//數組迴圈輸出1
foreach ($arr as $value) {
echo 'Value = '.$value.'<br />';
}
//數組迴圈輸出2
foreach ($arr as $key => $value) {
echo "Key: $key; Value: $value<br />\n";
}

二,join 把數組元素組合為一個字串
$in = join("', '", $arr);


三、foreach相關異常解決辦法
1,問題Warning: Invalid argument supplied for foreach() in 完善解決方案

解決方案:將foreach中的變數,用is_array()判斷一下,或強制轉化為array
例如

Php代碼

function getPartsNum($jsonStr){

$total = 0;

if( $jsonStr && ($jsonStr != 'NAN') && ($jsonStr != '[]') ) {

$detail = json_decode($jsonStr);

if(is_array($detail)){//或foreach ( (array)$detail as $d)

foreach ($detail as $d){

$total += $d->num;

}

}

}

return $total;

}

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.