到处都找到了删除php或mysql中重复条目的解决方案。但是所有这些解决方案都删除了整行,但我只想删除列的值。例如我在mysql中有这个SELECT:
SELECT HE_FRUIT as fruit, CA_FRUIT as candy, CA_FRUIT_NAME as name, CA_FRUIT_color as color
FROM fruits LEFT JOIN candy ON HE_FRUIT_ID = CA_FRUIT_ID
WHERE CA_FRUIT_COUNTRY LIKE '%usa%'
GROUP BY CA_FRUIT_TITLE
ORDER BY CA_FRUIT_PRIO, CA_FRUIT_HE
我打印数组,我明白了:
array
0 =>
array
fruit = "APPLE"
candy = "lolly"
name = "xxx"
color = "green"
1 =>
array
fruit = "APPLE"
candy = "gum"
name = "xxx"
color = "blue"
2 =>
array
fruit = "APPLE"
candy = "candy"
name = "xxx"
color = "red"
3 =>
array
fruit = "BANANA"
candy = "lolly"
name = "xxx"
color = "yellow"
我想要的是:
0 =>
array
fruit = "APPLE"
candy = "lolly"
name = "xxx"
color = "green"
1 =>
array
fruit = ""
candy = "gum"
name = "xxx"
color = "blue"
2 =>
array
fruit = ""
candy = "candy"
name = "xxx"
color = "red"
3 =>
array
fruit = "BANANA"
candy = "lolly"
name = "xxx"
color = "yellow"
因此,只有柱状水果的价值应该被移除,但其余部分应该保留。
有人知道如何解决这个问题,而不需要额外的代码吗?
提前非常感谢?
答案 0 :(得分:1)
试试这个:
<?php
$data = array(
0 => array(
'fruit' => "APPLE",
'candy' => "lolly",
'name' => "xxx",
'color' => "green"
),
1 => array(
'fruit' => "APPLE",
'candy' => "gum",
'name' => "xxx",
'color' => "blue"
),
2 => array(
'fruit' => "APPLE",
'candy' => "candy",
'name' => "xxx",
'color' => "red"
),
3 => array(
'fruit' => "BANANA",
'candy' => "lolly",
'name' => "xxx",
'color' => "yellow"
)
);
foreach($data as $i => $dataRow)
{
foreach($dataRow as $fieldName => $fieldValue)
{
for($j=0; $j<$i; $j++)
{
if($data[$j][$fieldName] == $fieldValue)
{
$data[$i][$fieldName] = '';
}
}
}
}
print_r($data);
?>
答案 1 :(得分:0)
您是否需要结果数组只是一维的?如果没有,我建议你可以将数组处理成一个多维数组,如下所示:
$array=array(
0 =>
array(
'fruit' => "APPLE",
'candy' => "lolly",
'name' => "xxx",
'color' => "green"),
1 =>
array(
'fruit' => "APPLE",
'candy' => "gum",
'name' => "xxx",
'color' => "blue"),
2 =>
array(
'fruit' => "APPLE",
'candy' => "candy",
'name' => "xxx",
'color' => "red"),
3 =>
array(
'fruit' => "BANANA",
'candy' => "lolly",
'name' => "xxx",
'color' => "yellow")
);
$output = array();
foreach( $array as $arrayItem ) {
if( !isset( $output[$arrayItem['fruit']]) ) {
$output[$arrayItem['fruit']] = array();
}
$outputItem = $arrayItem;
unset( $outputItem['fruit'] );
$output[$arrayItem['fruit']][] = $outputItem;
}
通过循环原始数据集可以达到相同的效果,您不需要创建一维PHP数组,然后再次处理它。这只是为了让例子更加清晰。
答案 2 :(得分:0)
SELECT DISTINCT
或array_unique()
和朋友不会在这里帮助您:您不希望禁止重复行,您想操纵他们有不同的水果:空的字符串。
所以你最终需要一个循环:
//Assumes your resultset is in $myarray
$fruits=array();
for ($i=0;$i<sizeof($myarray);$i++)
if (in_array($myarray[$i]['fruit'],$fruits)) $myarray[$i]['fruit']='';
else $fruits[]=$myarray[$i]['fruit'];