i have some dummy related data in my table "you can take a look at it bellow". i want to nest the data according to their relationships into one array.
Table Data:
+-----+------+--------+
| uid | name | parent |
+-----+------+--------+
| 1 | A | 0 |
| 2 | B | 1 |
| 3 | C | 1 |
| 4 | D | 2 |
| 5 | E | 3 |
| 7 | G | 3 |
| 9 | H | 4 |
| 10 | I | 4 |
| 11 | J | 7 |
+-----+------+--------+
the array is going to be like array('A' =>array('B'=>'D','C'=>array(...)).
am currently using codeigniter and here is what i've done
CODE
public function nestDataIntoArray($id)
{
$this->db->where('uid', $id);
$query = $this->db->get('binary_tbl');
$result = [];
if ($query->num_rows() > 0) {
foreach ($query->result() as $k) {
// secondLevel deep
$secondLevel = $this->getSubLevel($k->uid);
$secondLevelRowCount = $secondLevel->num_rows();
if ($secondLevelRowCount > 0 ) {
if ($secondLevelRowCount > 1) {
foreach ($secondLevel->result() as $key) {
// create second level deep array
$result[$k->name][$key->name][] = $this->getSubLevel($key->uid)->row('name');
// thirdLevel deep
$thirdLevel = $this->getSubLevel($key->uid);
$thirdLevelRowCount = $thirdLevel->num_rows();
if ($thirdLevelRowCount > 0) {
if($thirdLevelRowCount > 1){
foreach ($thirdLevel->result() as $tKey) {
// create third level deep array
$result[$k->name][$key->name][$tKey->name] = $this->getSubLevel($tKey->uid)->row('name');
}
}else{
foreach ($thirdLevel->result() as $tKey) {
$result[$k->name][$key->name][$tKey->name] = $this->getSubLevel($tKey->uid)->row('name');
}
}
} else {
$result[$k->name][$key->name] = $this->getSubLevel($key->uid)->result_array();
} //end thirdLevel deep
}
}
} else {
$result[$k->name] = $this->getSubLevel($key->uid)->row('name');
} // end second level deep
}
} else {
$result = NULL;
}
return $result;
}
private function getSubLevel($id)
{
return $this->db->select('*')->from('binary_tbl')->where('supermember', $id)->get();
}
upon invoking the nestDataIntoArray(1) method i got the following output
OUTPUT
array (size=1)
'A' =>
array (size=2)
'B' =>
array (size=2)
0 => string 'D' (length=1)
'D' => string 'H' (length=1)
'C' =>
array (size=3)
0 => string 'E' (length=1)
'E' => null
'G' => string 'J' (length=1)
this output seems to be fine but i really dont want that Zero index and some of the data still has one or two data related to them which i still have to loop through to get and that to me just seems to be alot of unnecessary coding. So the question is: which other better way can i achieve this and how do i get rid of that zero index?
At the moment I have a database structure like so:
| id | name | parent_id
| 1 | Human Resources | 0
| 2 | Marketing | 0
| 3 | Operations | 0
| 4 | Design | 0
| 5 | Marketing Design| 4
| 6 | Graphic Design | 4
| 7 | Print Design | 4
| 8 | Human Personal | 1
| 9 | Food Ops | 3
As you can see these are the departments within the business and also sub departments.
A sub-departments parent_id is the id of the department
do, for example:
id: 4, name: Design, parent_id: 0
id: 7, Print Design, parent_id: 4
Print Design is a sub department of design
I have called everything from the database in one query and now I need them in this structure:
$depts = array(
"Human Resources" => array("Human Personal"),
"Marketing" => array(),
"Operations" => array("Food Ops"),
"Design" => array("Marketing Design", "Graphic Design", "Print Design"),
...
);
so far I have:
foreach ($results as $result) {
if ($result['parent_id'] == 0) {
$parentCategories_arr[array($result['id'] => $result['name'])];
} else {
$returnedResults_arr[$result['parent_id']] = array($result['name']);
}
}
However I completely think that I have missed the point. so my question:
How do I loop through all the contents of that results and add the parent categories into an array with their sub categories as an array?
Maybe there is an easier way, but it works : (hate to say that sentence) - try to make it better maybe
$mFinalArray = fixMyArray($results);
print_r($mFinalArray);
function fixMyArray($results){
// Create categories - parent_id == 0
foreach($results as $index => $result) // $index = 0|1|2|3|4|5|6|7|8|9
if($result['parent_id'] == 0) // $result['parent_id'] = current item parent_id
$mCategories[$result['name']] = $result['id']; // $mCategories['Human Resources'] = 1|2|3|4
// Insert each data to the right parent
foreach($results as $index => $result) // $index = 0|1|2|3|4|5|6|7|8
if($result['parent_id'] != 0)
foreach($mCategories as $subindex => $category) // $subindex = Human Resources | Marketing | Operations | Design
if($result['parent_id'] == $category) // $category = 0|1|2|3|4
$mFinalArray[$subindex][] = $result['name']; // ex. $mFinalArray['Human Resources'][] = Human Personal
return $mFinalArray;
}
*Last line has an extra [ ] $mFinalArray[$subindex][ ]= $result['name'] . That means append to array.
Output :
Array
(
[Design] => Array
(
[0] => Marketing Design
[1] => Graphic Design
[2] => Print Design
)
[Human Resources] => Array
(
[0] => Human Personal
)
[Operations] => Array
(
[0] => Food Ops
)
)
I am sorry for my lazy title. I hope that a moderator could improve it so the database won't get infected.
I got the following code (forum.php);
<?php
$res = $db->query('
SELECT *
FROM forums_categories
ORDER BY category_id
');
while ($row = $db->fetch_array($res)) {
$categories = array(
'ID' => $row['category_id'],
'NAME' => $row['category_name']
);
echo '<pre>';
print_r($categories);
echo '</pre>';
}
And I got the following database structure;
|---------------|-------------------|
| category_id | category_name |
|---------------|-------------------|
| 1 | Example 1 |
| 2 | Example 2 |
| 3 | Example 3 |
| 4 | Example 4 |
| 5 | Example 5 |
| 6 | Example 6 |
|---------------|-------------------|
But my array only returns 1 value:
Array
(
[ID] => 1
[NAME] => Example 1
)
Oh and if somebody likes to know how my $db->fetch_array looks like:
<?php
function fetch_array($result)
{
return mysql_fetch_assoc($result);
}
How can I return all rows in my array? Thank you for reading and thank you for replying!
You're overwriting the previous value of $categories on each iteration
$categories[] = array(
'ID' => $row['category_id'],
'NAME' => $row['category_name']
);
You might also want to initialize an empty array
$categories = array();
before your loop to avoid warnings.
I'm working on a Bubble Chart using Highcharts. Here's a sample of my data:
name | price | quantity | count
--------+-------+----------+-------
Female | 2 | 3 | 5
Female | 3 | 12 | 10
Female | 5 | 6 | 15
Female | 1 | 7 | 25
Male | 3 | 5 | 7
Male | 2 | 9 | 11
Male | 5 | 7 | 23
Male | 4 | 4 | 14
I'm using PHP to query the data and encode to JSON:
$query = "SELECT name, price, quantity, count FROM sales WHERE id = $1";
$result = pg_prepare($db, "report", $query);
$result = pg_execute($db, "report", array($ID));
while ($row = pg_fetch_array($result, NULL, PGSQL_ASSOC))
{
$response['xdata'][$row['name']]['x'][] = $row['price'];
$response['xdata'][$row['name']]['y'][] = $row['quantity'];
$response['xdata'][$row['name']]['radius'][] = $row['count'];
}
echo json_encode($response);
However, the desired JSON format is as follows in order to properly plot the graph:
series: [{
name: 'Female',
marker:{
symbol:'circle',
fillColor:'rgba(24,90,169,.5)',
lineColor:'rgba(24,90,169,.75)',
lineWidth:1,
color:'rgba(24,90,169,1)',
states:{
hover:{
enabled:false
}
}
},
data: [{x:2,y:3,marker:{radius:5}},
{x:3,y:12,marker:{radius:10}},
{x:5,y:6,marker:{radius:15}},
{x:1,y:7,marker:{radius:25}}]
},{
name: 'Male',
marker:{
symbol:'circle',
fillColor:'rgba(238,46,47,.5)',
lineColor:'rgba(238,46,47,.75)',
lineWidth:1,
color:'rgba(238,46,47,1)',
states:{
hover:{
enabled:false
}
}
},
data: [{x:3,y:5,marker:{radius:7}},
{x:2,y:9,marker:{radius:11}},
{x:5,y:7,marker:{radius:23}},
{x:4,y:4,marker:{radius:14}}]
}]
My question is, how can I correctly process $query in PHP to get the desired JSON format as above and pass it to series through something like optionsBubble.series = data.xdata? Thanks a lot!
You'd first have to build the non-db-related parts into your PHP structure, e.g.
$data = array(
0 => array(
'name' => 'Female',
'marker' => array (
'symbol': 'circle'
etc....),
'data' => array() // database insertion occurs here
),
1 => array(
'name' => 'Male',
etc...
)
);
$locations = array('Female' => 0, 'Male' => 1, etc...) // reverse map your 'name' fields
while(...) {
$data[$locations[$row['name']]][data]['x'][] = $row['price'];
$data[$locations[$row['name']]][data]['y'][] = $row['quantity'];
^^^^^^^^^^^^^^^^^^^^^^^^--- reverse lookup to get right array index for 'name'
}
First I'm going to recommend you take a look at your SQL query, especially the part of WHERE id=$1. If I'm not mistaken (and on this I'm fairly sure.) your query is going to return one (1) row not many like what you probably want. I would recommend removing the WHERE clause and see if that solves your problem.
If not drop me a line and I'll see what else I see and we can go from there.
i have two db tables in my codeigniter project. As simplified summary,
page page_lang
------------------------------------- ----------------------------
id_page | id_menu | id_parent | level id_page | title | etc..
------------------------------------- ----------------------------
1 | 1 | 0 | 0 1 | Name 1 | etc..
2 | 1 | 1 | 1 2 | Name 1.1 | etc..
3 | 1 | 2 | 2 3 | Name 1.1.1 | etc..
4 | 1 | 2 | 1 4 | Name 1.2 | etc.
I am trying to create a dropdown select box which contains all page nested with indents as output like;
<option value="id_page">Name 1</option>
<option value="id_page"> » Name 1.1</option>
<option value="id_page"> - Name 1.1.1</option>
<option value="id_page"> » Name 1.2</option>
In this case, in need join page and page_lang and create a recursive loop, i quess.
But I am stacked on designing the fastest possible code. Thank you for any help.
Your recursive function will look something like this
function recursivePageOptions( $level, $nodes ) {
$set = array();
foreach ($nodes as $node) {
$nest = '';
for($x=1; $x<=$level; $x++)
$nest.= ' ';
$page = '<option value="'.$node['page']['id'].'">';
$page.= $nest . $node['page']['title'] . '</option>';
$set[] = $page;
if (isset($node['children'])) {
$set = array_merge(
$set,
recursivePageOptions( $level+1, $node['children'] );
);
}
}
return $set;
}
So what you need to do before this recursive function is called is get your page information into an array structure that looks like this:
[
'My Homepage' => [
'page' => ['My Homepage', 24, ... ],
'children' => [
'Level 1 Page' => [
'page' => ['Level 1 Page', 39, ... ],
'children' => [
'Level 2 Page' => [
'page' = ['Level 2 Page', 51, ... ]
]
]
],
'Another Level 1 Page' =< [
'page' => ['Another Level 1 Page', 56, ... ]
]
]
]
]
Its up to you to figure this part out in detail, essentially you will be getting rows out of the database and looping through them in such a way as to generate an array structure like the one above.