PHP:显示具有适当索引的关联数组
我已经完成了一个基本的SQL查询,然后在PHP中执行了一个WHILE循环来遍历它们。我大致构建了我想要的,但输出不是100% 我离得很近,但还不够近。对我的实际输出和期望输出有什么指导吗 下面的所有代码片段 我已经接近以下内容,但它为每条记录创建了一个新条目,而不是对它们进行分组PHP:显示具有适当索引的关联数组,php,arrays,Php,Arrays,我已经完成了一个基本的SQL查询,然后在PHP中执行了一个WHILE循环来遍历它们。我大致构建了我想要的,但输出不是100% 我离得很近,但还不够近。对我的实际输出和期望输出有什么指导吗 下面的所有代码片段 我已经接近以下内容,但它为每条记录创建了一个新条目,而不是对它们进行分组 $a["name"]["contacts"][] = array("name"=>$row["contact"],"address"=>$row["address_1"],"phone"=>array
$a["name"]["contacts"][] = array("name"=>$row["contact"],"address"=>$row["address_1"],"phone"=>array("type"=>$row["type"],"number"=>$row["number"]));
注释
查询可以返回一行或多行联系人。每个联系人可能有多个电话号码,或者只有一个。希望从下面的数据可以看出这一点。我不能在SQL中这样做,因为我只能执行非常简单的SQL语句,而没有函数
数据如下
PHP
输出
期望输出
只需将名称添加到每个关联数组,然后调用数组_值,将$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);
$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
)
)
)
)
)
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);