爆炸数组并运行foreach循环

时间:2015-10-11 10:07:28

标签: php

我的数据库中存储了以下字符串:[gallery ids="442,443,444"]

我想从ids获取值442443444并运行foreach循环。

所以它基本上会遍历ids内的所有整数。

如何使用PHP执行此操作?

3 个答案:

答案 0 :(得分:1)

您需要先集体提取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)可以更好地服务。

答案 1 :(得分:1)

您可以尝试这个小脚本:

<?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,....
}
?>

答案 2 :(得分:1)

试试这种方式

$txt = '[gallery ids="442,443"]';
preg_match_all('!\d+!', $txt, $match);
print_r($match); // get all matches data in an array