PHP - 爆炸由爆炸创建的数组中的每个项目

时间:2015-03-31 21:45:28

标签: php arrays loops explode

我的代码是......

$string ="foo:bar,bar,bar|foo2:bar2,bar2,bar2";

$first_array = explode("|", $string);

function split(&$block) {

$block = explode(":", $block);

}

array_walk($first_array, "split");

echo $block["0"]["0"];
echo "<br />";
echo $block["0"]["1"];

?>

感谢您的帮助。从我收集的内容来看,这应该是提供的代码的干净版本。这不会回应任何内容,也不提供代码。

2 个答案:

答案 0 :(得分:1)

这样可以解决问题:

$string ="foo:bar:bar:bar|foo2:bar2:bar2:bar2";

// first explode on |
$first_array = explode("|", $string);
// this function go on each lines of an array and transform each by a function
array_walk($first_array, function(&$item) {
         // so for each line explode with ':' as delimiter
         $item = explode(':', $item);
});

// To check all lines of the array
foreach($first_array as $line_array) {
     //my code for each sub-array
}

// To get only the last (second)
$second_sub = array_pop($first_array);

// if you want one dimension with all exploded you can use
// this function split with a regexp pattern
// "/[\|:,]+/" foreach "|" or ":" or ","  split the string
preg_split("/[\|:,]+/", $string);

答案 1 :(得分:0)

不要使用$ block,因为它是在另一个范围内定义的,而且你不能将“split”作为你的函数的名称,因为它是一个现有的php函数

$string ="foo:bar,bar,bar|foo2:bar2,bar2,bar2";

$first_array = explode("|", $string);

function mysplit(&$block) {

$block = explode(":", $block);

}

array_walk($first_array, "mysplit");

echo $first_array[0][0];
echo "<br />";
echo $first_array[0][1];