Reputation: 3802
I've done a basic SQL query and then a WHILE loop in PHP to loop through them. I've roughly built what I want but the output isn't 100%
I'm close but not close enough. Any guidance on my actual output vs. desired?
All code snippets below.
I have got close with the following but it creates a new entry for each record rather than grouping them
$a["name"]["contacts"][] = array("name"=>$row["contact"],"address"=>$row["address_1"],"phone"=>array("type"=>$row["type"],"number"=>$row["number"]));
NOTES
A query can return one or many rows (contacts). Each contact could have multiple phone numbers against them (or just one). Hopefully this is obvious from the data below. I can't do this in SQL as I can only perform very simple SQL statements and no functions.
DATA FOR BELOW
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"]);
}
OUTPUT
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
)
)
)
)
DESIRED OUTPUT
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
)
)
)
)
)
Upvotes: 0
Views: 69
Reputation: 1812
Simply add the name to each associative array and then call array_values to convert $a into a simple array:
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);
Upvotes: 1