我在foreach
循环中工作,PARTS我的代码如下:
foreach ($query->rows as $row) {
$myarray = explode(",",$row['text']);
print_r($myarray);
}
以上的输出结果如下:
Array
(
[0] = Charcoal
[1] = Natural Gas
[2] = Combo
)
Array
(
[0] = Charcoal
[1] = Propane
[2] = Combo
)
Array
(
[0] = Charcoal
[1] = Propane
[2] = Natural Gas
[3] = Combo
)
Array
(
[0] = coal
)
Array
(
[0] = Natural Gas
[1] = Wood
)
是的,我看到有类似的问题。但他们的答案似乎都不适合我。我认为这可能是因为我在foreach循环中工作。无论哪种方式,我想知道是否有办法让我的输出看起来像这样:
Array
(
[0] = Charcoal
[1] = Natural Gas
[2] = Combo
)
Array
(
[0] = Propane
)
Array
(
[0] = Coal
)
Array
(
[0] = wood
)
所有重复项都没有丢失,也没有丢失此数组的格式。代码我试过..但是"也许"错了是:
$input = array_map("unserialize", array_unique(array_map("serialize", $input)));
Sharanya Dutta的编辑:
我有很多其他代码,但基本上这就是我试图使用它的地方。
$arr = array();
foreach($query->rows as $row){
$_arr = explode(",", $row["text"]);
$diff = array_values(array_diff($_arr, $arr));
if($diff !== array()) print_r($diff);
$arr = array_merge($arr, $_arr);
$output[$row['attribute_id']]['values'][] = $diff; // <--- USE IT HERE
}
答案 0 :(得分:2)
使用数组(以下代码中为$arr
)存储值,print_r
仅存储与已存储值不同的值:
$arr = array();
foreach($query->rows as $row){
$_arr = explode(",", $row["text"]);
$diff = array_values(array_diff($_arr, $arr));
if($diff !== array()) print_r($diff);
$arr = array_merge($arr, $_arr);
}
您甚至可以在$diff
循环的最后一行之后使用foreach
:
$arr = array();
foreach($query->rows as $row){
$_arr = explode(",", $row["text"]);
$diff = array_values(array_diff($_arr, $arr));
$arr = array_merge($arr, $_arr);
if($diff !== array()) print_r($diff);
}