Dividing rows into dimensional array - php

I want to get the list for the food from the database into array order by category so that I can split each entry into the categories.
Like this..
$menu = array(
'Appetizers' => array(
'Chicken Tenders' => '$2.99',
'Twisted Chips' => '$1.99'
),
'Seafood' => array(
'Bayou Tilapia' => '$4',
'Grill Atlantic Salmon' => '$3.99'
),
'Steaks & Combos' => array(
'Cowboy Grande Sirloin' => '$7.99'
)
)
Here is what I did.
$db->Query("SELECT menuTitle,menuCategory,menuPrice FROM menu");
$menu = array();
while ($row = $db->Row()) {
$a = array($row->menuCategory => array($row->menuTitle=>$row->menuPrice));
array_push($menu,$a);
}
It doesn't seem to work. Would you please advise how to achieve this?

replace:
$a = array($row->menuCategory => array($row->menuTitle=>$row->menuPrice));
array_push($menu,$a);
with:
$menu[$row->menuCategory][$row->menuTitle]=$row->menuPrice;

The code in the while block is not exactly seeming right, as you always redefine the $a array while iterating.
while ($row = $db->Row()) {
$a[ $row->menuCategory ][ $row->menuTitle] = $row->menuPrice;
array_push($menu,$a);
}
This way, you will only append new keys to the array.

$db->Query("SELECT menuTitle,menuCategory,menuPrice FROM menu");
$menu = array(); $a = array();
while ($row = $db->Row()) {
$a[$row->menuCategory ][$row->menuTitle] = $row->menuPrice;
}
array_push($menu,$a);
echo "<pre>";print_r($menu);echo "</pre>";

Related

Group together array elements

I have an array in PHP:-
$arr = ["BX_NAME0","BX_NAME1","BX_NAME2","BX_categoryName0","BX_categoryName1","BX_categoryName2","BHA_categories0","BHA_categories1","BHA_categories2"]
Here I want to group together elements based on same ending integer together in json like
$post_data = array(
'0' => array(
'BX_NAME0' => $item_type,
'BX_categoryName0' => $string_key,
'BHA_categories0' => $string_value
),
'1' => array(
'BX_NAME1' => $item_type,
'BX_categoryName1' => $string_key,
'BHA_categories1' => $string_value
),
);
I have Used:- filter_var($key , FILTER_SANITIZE_NUMBER_INT);
to get the integer part of the array elements but don't known how to group them further.
You can do it like below using preg_match():-
$new_array = array();
foreach ($arr as $ar){
preg_match_all('!\d+!', $ar, $matches); //get the number from string
$new_array[$matches[0][0]][$ar] = '';
}
echo "<pre/>";print_r($new_array);
Output:- https://eval.in/715548
It should be something like this:-
$arr = array("BX_NAME0","BX_NAME1","BX_NAME2","BX_categoryName0","BX_categoryName1","BX_categoryName2","BHA_categories0","BHA_categories1","BHA_categories2");
$post_data = array();
foreach($arr as $value) {
$key = filter_var($value , FILTER_SANITIZE_NUMBER_INT);
if(isset($post_data[$key]) && !is_array($post_data[$key])) {
$post_data[$key] = array();
}
$post_data[$key][] = $value;
}
print_r($post_data);
Tested and works
However, I suggest you use substr() to get the last character of the array item, for performance and stuff..
By using filter_var() method
$arr = ["BX_NAME0","BX_NAME1","BX_NAME2","BX_categoryName0","BX_categoryName1","BX_categoryName2","BHA_categories0","BHA_categories1","BHA_categories2"];
foreach($arr as $a){
$int = filter_var($a, FILTER_SANITIZE_NUMBER_INT);
$newarr[$int][$a] = '';
}
print_r($newarr);
Output:-https://eval.in/715581

Store array into array of array

Im generating Chart4PHP.
In sample it takes data like this
$p->data = array(array(array("2010/10",-48),array("2011/01",238),array("2011/02",395)));
I have array "rows" constructed of row[date][units].
Im storing it in this way:
$rows = array();
for(...)
{
$row[date] = $mydate;
$row[units]= $myunits;
$rows[]=$row;
}
What I should make additionally to be able to use it as $p->data = $rows;
To add the extra array container, call array() with the rows array as the argument.
$data = array(array('date' => "2010/10", 'units' => -48),
array('date' => "2011/01", 'units' => 238),
array('date' => "2011/02", 'units' => 395));
foreach ($data as $d) {
$mydate = $d['date'];
$myunits = $d['units'];
$rows[] = array($mydate, $myunits);
}
$p->data = array($rows);

Handling foreach or forloop with array values PHP MYSQL

Output Array (The variable name is $r)
Array
(
[Jan-14] => 7588793.52
[Feb-14] => 9944970.87
[Mar-14] => 8567790.20
[Apr-14] =>
[May-14] =>
[Jun-14] =>
[Jul-14] =>
[Aug-14] =>
[Sep-14] =>
[Oct-14] =>
[Nov-14] =>
[Dec-14] =>
)
What I have done so far is..
while($r = mysql_fetch_assoc($query)) {
$series1['data'][] = $r['Jan-14'];
$series2['data'][] = $r['Feb-14'];
.... it will go till Dec-14.......
array_push($result,$series1);
array_push($result,$series2);
.... it will go till Dec-14.......
}
Expected Output:
The code should look something like this this (dynamic)
while($r = mysql_fetch_assoc($query)) {
for($i=1;$i<=count($r);$i++){
$series.$i['data'][] = ??????????
array_push($result,$series.$i);
..................
}
}
Help me out. Don't talk about the db structure or normalization. The db was given by my client.
Thanks,
Kimz
Do you mean like this?
$result = array();
foreach($r as $month => $value) {
$result[] = array('data' => array($value));
}

Multidimensional PHP array from SQL, for json_encode

I'm struggling trying to create a three-dimensional array from my DB, and encoding it to JSON.
My DB contains 3 tables, timeline_table, content_table and pic_table. I want the following structure for my JSON:
{"timeline:"{"content":{"pictures:"{}}}}
Here's my current PHP code:
$get = 1;
$results = mysql_query("
SELECT timeline_table.*, content_table.*, pic_table.*
FROM timeline_table
JOIN content_table
ON content_table.tl_ID = timeline_table.tl_ID
JOIN pic_table
ON pic_table.content_ID = content_table.content_ID
WHERE timeline_table.tl_ID = $get
") or die(mysql_error());
while($row = mysql_fetch_assoc($results)){
$timeline['timeline'][] = array(
'tl_ID' => $row['tl_ID'],
'tl_name' => $row['tl_name'],
'tl_date' => $row['tl_date'],
'tl_desc' => $row['tl_desc'],
);
$timeline['timeline']['content'][] = array(
'content_ID' => $row['content_ID'],
'tl_ID' => $row['tl_ID'],
'content_time' => $row['content_time'],
'content_date' => $row['content_date'],
'content_title' => $row['content_title'],
'content_content' => $row['content_content'],
'content_category' => $row['content_category'],
'content_mapLat' => $row['content_mapLat'],
'content_mapLng' => $row['content_mapLng'],
'content_zoomLvl' => $row['content_zoomLvl'],
);
$timeline['timeline']['content']['pictures'][] = array(
'pic_ID' => $row['pic_ID'],
'content_ID' => $row['content_ID'],
'pic_path' => $row['pic_path'],
'pic_desc' => $row['pic_desc'],
'pic_link' => $row['pic_link']
);
}
echo stripslashes(json_encode($timeline));
}
I have also tried with 1 query for each table, and using 3 while loops to fill the array. I believe one query is the better way to go, but please correct me if I'm wrong. This php gives me the following JSON:
{
"timeline":{
"0":{
"tl_ID":"1",
"tl_name":"Tidslinje 1",
"tl_date":"2013-01-16",
"tl_desc":"Test av tl_table"
},
"content":{
"0":{
"content_ID":"1",
"tl_ID":"1",
"content_time":"16:00:00",
"content_date":"2013-01-17",
"content_title":"Test",
"content_content":"Test content number one.",
"content_category":"test",
"content_mapLat":null,
"content_mapLng":null,
"content_zoomLvl":null
},
"pictures":[
{
"pic_ID":"1",
"content_ID":"1",
"pic_path":"http://i.imgur.com/F6RmDFt.jpg",
"pic_desc":"katt",
"pic_link":"http://i.imgur.com/F6RmDFt.jpg"
},
{
"pic_ID":"3",
"content_ID":"3",
"pic_path":"http://i.imgur.com/POum7eK.jpg",
"pic_desc":"seamonster",
"pic_link":"http://i.imgur.com/POum7eK.jpg"
}
]
}
}
}
All pictures regardless of content_ID comes in one array, and if I add more content, contents with ID 2,3 etc comes under the picture array. I want the pictures in arrays under the content_ID they belong to, and the content under the timeline they belong to. I also want the array keys to be "timeline", "content" and "pictures", instead of integers.
Hopefully this is understandable, any help is greatly appreciated!
EDIT: Solved!
$get = 1;
$result = mysql_query("
SELECT t.tl_ID, t.tl_name, t.tl_date, t.tl_desc, c.content_ID, c.content_time, c.content_date, c.content_title, c.content_content, c.content_category, p.pic_ID, p.pic_path, p.pic_desc, p.pic_link
FROM timeline_table t
LEFT JOIN content_table c ON t.tl_ID = c.tl_ID
LEFT JOIN pic_table p ON c.content_ID = p.content_ID
WHERE t.tl_ID = $get
ORDER BY t.tl_ID, c.tl_ID, p.content_ID
") or die(mysql_error());
$jsonData = array();
$tl_ID = 0;
$content_ID = 0;
$timelineIndex = -1;
$contentIndex = -1;
while($row = mysql_fetch_assoc($result)){
if($tl_ID != $row['tl_ID']){
$timelineIndex++;
$contentIndex = -1;
$tl_ID = $row['tl_ID'];
$jsonData[$timelineIndex]['tl_ID'] = $row['tl_ID'];
$jsonData[$timelineIndex]['tl_name'] = $row['tl_name'];
$jsonData[$timelineIndex]['tl_date'] = $row['tl_date'];
$jsonData[$timelineIndex]['tl_desc'] = $row['tl_desc'];
$jsonData[$timelineIndex]['content'] = array();
}
if($content_ID != $row['content_ID']){
$contentIndex++;
$content_ID = $row['content_ID'];
$jsonData[$timelineIndex]['content'][$contentIndex]['content_ID'] = $row['content_ID'];
$jsonData[$timelineIndex]['content'][$contentIndex]['content_time'] = $row['content_time'];
$jsonData[$timelineIndex]['content'][$contentIndex]['content_date'] = $row['content_date'];
$jsonData[$timelineIndex]['content'][$contentIndex]['content_title'] = $row['content_title'];
$jsonData[$timelineIndex]['content'][$contentIndex]['content_content'] = $row['content_content'];
$jsonData[$timelineIndex]['content'][$contentIndex]['content_category'] = $row['content_category'];
$jsonData[$timelineIndex]['content'][$contentIndex]['pictures'] = array();
}
$jsonData[$timelineIndex]['content'][$contentIndex]['pictures'][] = array(
'pic_ID' => $row['pic_ID'],
'pic_path' => $row['pic_path'],
'pic_desc' => $row['pic_desc'],
'pic_link' => $row['pic_link']
);
}
echo stripslashes(json_encode($jsonData));
}
Edited, try this one:
$timeline['timeline'][] = array(
'tl_ID' => $row['tl_ID'],
'tl_name' => $row['tl_name'],
'tl_date' => $row['tl_date'],
'tl_desc' => $row['tl_desc'],
'content' => array(
'content_ID' => $row['content_ID'],
'tl_ID' => $row['tl_ID'],
'content_time' => $row['content_time'],
'content_date' => $row['content_date'],
'content_title' => $row['content_title'],
'content_content' => $row['content_content'],
'content_category' => $row['content_category'],
'content_mapLat' => $row['content_mapLat'],
'content_mapLng' => $row['content_mapLng'],
'content_zoomLvl' => $row['content_zoomLvl'],
'pictures' => array(
'pic_ID' => $row['pic_ID'],
'content_ID' => $row['content_ID'],
'pic_path' => $row['pic_path'],
'pic_desc' => $row['pic_desc'],
'pic_link' => $row['pic_link']
);
);
);

Dynamic array key in while loop

I'm trying to get this working:
I have an array that gets "deeper" every loop. I need to add a new array to the deepest "children" key there is.
while($row = mysql_fetch_assoc($res)) {
array_push($json["children"],
array(
"id" => "$x",
"name" => "Start",
"children" => array()
)
);
}
So, in a loop it would be:
array_push($json["children"] ...
array_push($json["children"][0]["children"] ...
array_push($json["children"][0]["children"][0]["children"] ...
... and so on. Any idea on how to get the key-selector dynamic like this?
$selector = "[children][0][children][0][children]";
array_push($json$selector);
$json = array();
$x = $json['children'];
while($row = mysql_fetch_assoc($res)) {
array_push($x,
array(
"id" => "$x",
"name" => "Start",
"children" => array()
)
);
$x = $x[0]['children'];
}
print_r( $json );
Hmmm - maybe better to assign by reference:
$children =& $json["children"];
while($row = mysql_fetch_assoc($res)) {
array_push($children,
array(
"id" => "$x",
"name" => "Start",
"children" => array()
)
);
$children =& $children[0]['children'];
}
$json = array();
$rows = range('a', 'c');
foreach (array_reverse($rows) as $x) {
$json = array('id' => $x, 'name' => 'start', 'children' => array($json));
}
print_r($json);
If you want to read an array via a string path, split the string in indices, and then you can do something like this to get the value
function f($arr, $indices) {
foreach ($indices as $key) {
if (!isset($arr[$key])) {
return null;
}
$arr = $arr[$key];
}
return $arr;
}

Categories