0

我有这个作为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
4

2 回答 2

0

这里真的没有充分的理由使用 foreach 作为输出。只需explode(),然后根据需要输出字段会容易得多(请注意,我构造了一个数组并在其上使用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解决这个问题,您首先要为自己构建一个“位置名称”数组(第一、第二、第三等),然后遍历 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;
}
于 2014-10-23T10:28:41.257 回答
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++;
}
于 2014-10-23T10:29:09.140 回答