我已经完成了一个基本的SQL查询,然后在PHP中执行一个WHILE循环来遍历它们。我已经大致建立了我想要的,但产出不是100%
我离得很近但还不够近。对我的实际输出和期望有什么指导吗?
下面所有的代码片段。
我已经接近了以下内容,但是它为每个记录创建了一个新条目,而不是对它们进行分组。
$a["name"]["contacts"][] = array("name"=>$row["contact"],"address"=>$row["address_1"],"phone"=>array("type"=>$row["type"],"number"=>$row["number"]));注意到
查询可以返回一行或多行(联系人)。每个联系人都可能有多个针对他们的电话号码(或者只有一个)。希望从下面的数据可以看出这一点。我不能在SQL中这样做,因为我只能执行非常简单的SQL语句,而不能执行任何函数。
数据在以下
Contact | Address_1 | Type | Number
-------------------------------------------------
Barry | | Home Mobile Phone | 666
Barry | | Home Phone | 888
Joanne | | Home Mobile Phone | 987654
Joanne | | Home Phone | 123456$res = RNCPHP\ROQL::query( "SELECT * FROM resource.contact_emergency WHERE collar = '".$row."'" )->next();
$a = Array();
while($row = $res->next()) {
$a[$row["contact"]]["address"] = $row["address_1"];
$a[$row["contact"]]["phone"][] = array("type"=>$row["type"],"number"=>$row["number"]);
}输出
Array
(
[Barry] => Array
(
[address] =>
[phone] => Array
(
[0] => Array
(
[type] => Home Mobile Phone
[number] => 666
)
[1] => Array
(
[type] => Home Phone
[number] => 888
)
)
)
[Joanne] => Array
(
[address] =>
[phone] => Array
(
[0] => Array
(
[type] => Home Mobile Phone
[number] => 987654
)
[1] => Array
(
[type] => Home Phone
[number] => 123456
)
)
)
)期望输出
Array
(
[person] => Array
(
[0] => Array
(
[name] => Barry
[address] =>
[phone] => Array
(
[0] => Array
(
[type] => Home Mobile Phone
[number] => 666
)
[1] => Array
(
[type] => Home Phone
[number] => 888
)
)
)
)
(
[1] => Array
(
[name] => Joanne
[address] =>
[phone] => Array
(
[0] => Array
(
[type] => Home Mobile Phone
[number] => 987654
)
[1] => Array
(
[type] => Home Phone
[number] => 123456
)
)
)
)
)发布于 2018-08-28 16:11:25
只需将名称添加到每个关联数组中,然后调用array_values将$a转换为简单数组:
while($row = $res->next()) {
$a[$row["contact"]]["name"] = $row["contact"];
$a[$row["contact"]]["address"] = $row["address_1"];
$a[$row["contact"]]["phone"][] = array("type"=>$row["type"],"number"=>$row["number"]);
}
$b['person'] = array_values($a);https://stackoverflow.com/questions/52061928
复制相似问题