我已经完成了基本的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
PHP
$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
)
)
)
)
)
答案 0 :(得分:1)
只需将名称添加到每个关联数组中,然后调用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);