Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php multi-dimensional array from mysql result

I have a mysql table that looks like this:

id | uid | title     | description | parent 1  |  1  | Portraits | desc.       | photostream 2  |  1  | Abstract  | descr.      | photostream 

and I am trying to build a multi-dimensional array that would end up looking like this:

Array (       [0]           [id] => 1           [uid] => 1           [title] => Portraits           [description] => desc.           [parent] => photostream       [1]           [id] => 2           [uid] => 1           [title] => Abstract           [description] => descr.           [parent] => photostream ) 

I am using the select query:

$query = mysql_query(   "SELECT * FROM `table` WHERE `uid`='1' ORDER BY `id` DESC"); 

Does anyone know how to do this? Thanks, Levi

like image 789
Levi Self Avatar asked Feb 19 '11 22:02

Levi Self


2 Answers

$query = mysql_query("SELECT * FROM table WHERE uid = '1' ORDER BY id DESC"); $results = array(); while($line = mysql_fetch_array($query, MYSQL_ASSOC)){     $results[] = $line; } 
like image 148
KeatsKelleher Avatar answered Sep 20 '22 14:09

KeatsKelleher


This does not include the sql functions for gathering the data but I made a table for my issue (was the same exact problem) This is my table also by the way. So its more of example than an explanation.

This is not a full on explanation but is a example code.


TABLE:
[ ID | Parent | name |href | title ]


CODE:

            foreach ($query->result_array() as $row) {     if ($row['parent'] === null)         $data[$row['id']][0]= '<a href="'.$row['href'].'"'.($row['title']!==null)?'title="'.$row['title'].'"':''.'>'.$row['name'].'</a>';     else      {         $temp = '<a href="'.$row['href'].'"'.($row['title']!==null)?'title="'.$row['title'].'"':''.'>'.$row['name'].'</a>';         array_push($data[$row['parent']],$temp);     } } 

I used this to generate my links for my navbar. Then I used a function to make a multi level list out of them. For my issue. Its very similar issue but this was my solution.

If you would like. Instead of making your own version. I can make a similar code using your database scheme for the data instead..

Warning: It seems this might only work on a two level layout at moment. Ill improvise code some more and post the next version of my snippet.

like image 39
CoasterChris Avatar answered Sep 18 '22 14:09

CoasterChris