我有以下字符串存儲在我的數據庫:[gallery ids="442,443,444"]
。爆炸陣列和運行foreach循環
我想從ids
即442
,443
,444
取值並運行一個foreach循環。
所以它基本上會遍歷ids
內的所有整數。
我該怎麼用PHP做到這一點?
我有以下字符串存儲在我的數據庫:[gallery ids="442,443,444"]
。爆炸陣列和運行foreach循環
我想從ids
即442
,443
,444
取值並運行一個foreach循環。
所以它基本上會遍歷ids
內的所有整數。
我該怎麼用PHP做到這一點?
您需要先提取ID,然後將它們組成一個數組。
list (,$rawIds) = preg_split('#"#', $string);
,然後爆炸的ID:
$ids = preg_split('#,\\s*#', $rawIds);
的\ S *照顧可能空格(如「21,22
例如,你可以使用雙引號分割字符串,23,24,25「)。
在您使用$ids
作爲數組這一點:
foreach ($ids as $index => $id) {
print "ID #{$index} is {$id}\n";
}
ID #0 is 5
ID #1 is 8
ID #2 is 12
不過,你最好驗證字符串是怎麼創建的:例如如果是JSON的話,最好使用json_decode($string, true)
。
你可以試試這個小腳本:
<?php
// get the value from the Database
$ids = $record; // get some procedure to get the value from the database.
// explode the value to get the list ids
$list = explode("=",$ids);
// get the list ids only
$elements = str_replace("\"","",$list[1]);
// extract all ids from the list
$array_list = explode(",",$elements);
// trigger loop to get each value
foreach($array_list as $ value){
echo $value."<br />"; // value for each element, i.e. 442, 443, 444,....
}
?>
嘗試這種方式
$txt = '[gallery ids="442,443"]';
preg_match_all('!\d+!', $txt, $match);
print_r($match); // get all matches data in an array
這是完美的。你能解釋我如何在每個ID上使用foreach循環嗎? – michaelmcgurk
謝謝@lserni :) – michaelmcgurk