0

我正在从一个while循环生成一个数组,我想最终使用这个数组来显示数据。

while($row = $database->fetch(PDO::FETCH_ASSOC)
{

     $value_1 = $row['value_1'];
     $value_2 = $row['value_2'];

     $data[] = array("value_1"=>$value_1,"value_2"=>$value_2);

}

所以 $data[] 会显示使用print_r我得到这样的东西:

Array
(
    [0] => Array
        (
            [value_1] => Hello World
            [value_2] => venus
        )

    [1] => Array
        (
            [value_1] => Hello World
            [value_2] => pluto
        )

    [2] => Array
        (
            [value_1] => Hello Moon
            [value_2] => Halloween
        )

)

我的问题是,如果我想获取所有数据但合并相同的值,我将如何进行 foreach 循环或显示这种方式?

Ex:

Hello World to venus pluto
Hello Moon to Halloween

我知道这些句子没有意义,但正如你所见,Hello World 将被合并,我需要在两者之间添加一个“to”value_1value_2

希望我的问题可以理解。

谢谢!

4

3 回答 3

2

尝试这样的事情。(未测试)

$match = array();
foreach($data as $d) {
    if (isset($match[$d['value_1']])) {
        $match[$d['value_1']] = $match[$d['value_1']].' '.$d['value_2'] ;
    } else {
        $match[$d['value_1']] = $d['value_1']. ' to '. $d['value_2'];
    }
}

print_r($match);
于 2012-11-01T07:02:17.167 回答
0

我认为首先你需要创建新数组,如下所示:

$new_array = array();
//consider your original array is $data
foreach($data as $row){
    if (array_key_exists($row['value_1'], $new_array)) {
       $new_array[$row['value_1']] = $new_array[$row['value_1']]. " ". 
                                     $row['value_2'];
    }
    else {
        $new_array[$row['value_1']] = $row['value_2'];
    }
}

然后通过迭代显示它:

foreach($new_array as $key => $value){
   echo $key ."to". $value;
}
于 2012-11-01T07:19:39.323 回答
-1
foreach($data as $d) {

    echo $d['value_1'], ' to ', $d['value_2']; // this is if you want to echo the content

    // this code is to insert 'to' in the middle of value_1 and value_2
    $value_2 = $d['value_2'];

    unset($d['value_2']);

    array_push($d, "to", $value_2);

    unset($value_2);

}

此外,您不需要将 $row 值分配给另一个值:

$value_1 = $row['value_1']; // remove this
$value_2 = $row['value_2']; // remove this

$data[] = array("value_1" => $row['value_1'], "value_2" => $row['value_2']);
于 2012-11-01T06:54:28.350 回答