MySQL CONCAT_WS三列,爆炸后回显结果为foreach循环()

时间:2014-10-23 10:06:43

标签: php mysql while-loop explode concat-ws

我的结果来自MySQL(存储为$result

+-------------------------------------------------------------------------+
| CONCAT_WS('::', p.isMobile, p.contact_phone_id, p.contact_phone_number) |
+-------------------------------------------------------------------------+
| 0::1::123                                                               |
| 1::2::456                                                               |
| 0::3::789                                                               |
| 1::4::987                                                               |
| 0::5::654                                                               |
| 0::6::321                                                               |
| 1::7::123                                                               |
| 1::11::456                                                              |
+-------------------------------------------------------------------------+

然后在while循环中,我为每一行使用explode(),如:explode('::', $result)。如何使用foreach()输出这样的数据(例如while迭代中的前三行):

Row 1: The first column is 0, the second column is 1, the third column is 123
Row 2: The first column is 1, the second column is 2, the third column is 456
Row 3: The first column is 0, the second column is 3, the third column is 789

2 个答案:

答案 0 :(得分:0)

在这里使用foreach输出真的没有理由。只需爆炸(),然后根据需要输出字段就容易多了 (注意我构造了一个数组并在其上使用了array_shift()来模拟从数据库中获取行):

<?php
$data = ['0::1::123', '1::2::456', '0::3::789', '1::4::987', '0::5::654', '0::6::321', '1::7::123', '1::11::456'];

$rownum = 0;
while($row = array_shift($data)) {
    echo "Row $rownum: ";
    $fields = explode('::', $row);
    echo "The first column is {$fields[0]}, the second column is {$fields[1]}, the third column is {$fields[2]}";
    echo "\n";
    ++$rownum;
}

但是,如果您真的依赖于使用foreach来解决问题,那么您首先要自己构建一系列&#34;位置名称&#34; (第一个,第二个,第三个等),然后遍历THAT,并在生成输出时从$ row数组中拉出相同的键:

<?php
$data = ['0::1::123', '1::2::456', '0::3::789', '1::4::987', '0::5::654', '0::6::321', '1::7::123', '1::11::456'];

$positions = ['first', 'second', 'third'];

$rownum = 0;
while($row = array_shift($data)) {
    echo "Row $rownum: ";
    $fields = explode('::', $row);
    $output = "";
    foreach($positions as $pos => $posName) {
        $output .= "the {$posName} column is {$fields[$pos]}, ";
    }
    $output = substr($output, 0, -2); // trim that trailing comma

    echo "$output\n";
    ++$rownum;
}

答案 1 :(得分:0)

试试这个。

$rowNumber = 1;
foreach($result as $value)
{
    $field = explode('::', $value);
    echo "Row {$rowNumber}: The first column is {$filed[0]}, the second column is {$field[1]}, the third column is {$field[2]}\n";

    $rowNumber++;
}