I'm having trouble tackling this one. I have a set of data that is returned from a MySQL query like this:
url | users
https://www.facebook.com/ | patrick
https://www.google.com/ | patrick
https://www.reddit.com/ | bob
https://www.bing.com/ | bob
https://www.yahoo.com/ | bertha
where '|' is the field separator.
I need to parse this data using PHP to form a multidimensional array that looks like this:
patrick
https://www.facebook.com/
https://www.google.com/
bob
https://www.reddit.com/
https://www.bing.com/
bertha
https://www.yahoo.com/
Any assistance would be appreciated.
Assuming you know how to get results out of the database with PHP, I would go with something like this;
while($row = $result->fetch_assoc()) {
$array[$row['users']][] = $row['url'];
}
You will get an array with the user as the first key, and a numeric as the second, with the url as the value, as follows;
Array (
patrick => Array (
[0] => https://www.facebook.com/
[1] => https://www.google.com/
)
bob => Array (
[0] => https://www.reddit.com/
[1] => https://www.bing.com/
)
bertha => Array (
[0] => https://www.yahoo.com/
)
)
Note: I have used the object orientated style mysqli function here. If you are still using mysql_
functions, please migrate to either MySQLi or PDO as soon as possible.
Hope this helps.