Creating associative array from object - php

I currently have an array that is building with the correct data by looping an object but it's giving the incorrect format:
$priceResult = array();
foreach($prices->categories as $category){
$priceResult[] = $category->category_name;
$priceResult[] = $category->category_desc;
$priceResult[] = $category->category_code;
foreach($category->products as $product){
$priceResult[] = $product->product_info->item->item_code;
foreach ($product->product_info->details as $details) {
$priceResult[] = $details->description;
$priceResult[] = $details->color;
$priceResult[] = $details->sector;
}
$priceResult[] = $product->product_info->code;
$priceResult[] = $product->product_info->item->description;
$priceResult[] = $product->product_info->item->item_type->quantity;
foreach(get_object_vars($product->prices) as $amount){
$priceResult[] = $amount;
}
}
}
This isn't associative though.
So currently, say I have one category with two products then they all print out as a single array
array({
1:category_name
2:category_desc
3:category_code
4:item_code
5:description
6:color
7:sector
8:code
9:description
10:quantity
11:amount
12:item_code
13:description
14:color
15:sector
16:code
17:description
18:quantity
19:amount
})
I'd like to get a structure where the parent level is the category_code with it's name and description, then each item_code and their own info like so:
array({
category_name
category_desc
category_code
Array(
1: item_code array(
details array(
description
color
sector
)
code
description
quantity
amount)
2: item_code array(
details array(
description
color
sector
)
code
description
quantity
amount)
)
})
How can I modify this to create the levels like I need so that it formats properly when I export to a spreadsheet

You need to split you code and init new object in the loop.
Consider the following (notice the comment in the code)
$allCategoryResult= array(); // init at first - notice naming as category and not prices
foreach($prices->categories as $category){
$categoryItem = array(); // as current category to populate
// give name to the keys and not just numbers
$categoryItem["name"] = $category->category_name;
$categoryItem["desc"] = $category->category_desc;
$categoryItem["code"] = $category->category_code;
foreach($category->products as $product){
$productItem = array(); // new product, so init new array for him
// fill all the item data with name - maybe you will need to fix the paths here
$productItem["details"] = array(); // init empty array for all the details elements
foreach ($product->product_info->details as $details) {
$detailsItem = array(); // init details array for each detail element
$detailsItem["description"] = $details->description;
$detailsItem["color"] = $details->color;
$detailsItem["sector"] = $details->sector;
$productItem["details"][] = $detailsItem; // add the detail element to the product array
}
$productItem["code"] = $product->product_info->code;
$productItem["itemDescription"] = $product->product_info->item->description;
$productItem["quantity"] = $product->product_info->item->item_type->quantity;
$productItem["amount"] = get_object_vars($product->prices);
$itemCode = $product->product_info->item->item_code;
categoryItem[$itemCode] = $productItem; // add the product to category array by his code
}
$allCategoryResult[] = $categoryItem; //add the category to all category array
}
Writing this without see you actual data is pretty hard - so I guess you will have to modify it to fit your data.
But I hop you get the idea. Good luck!

Related

Update One JSON Field in Database - CodeIgniter

I have a JSON field called 'spec' and there are about 10 other items in this in JSON format. I need to only update the quantity.
Although when I try this method, it deletes everything else in it and just sets spec = quantity.
Heres what I have so far.
$pass_coupon_id = $this->pass_coupon_id();
$coupon_array = $this->db->query("SELECT * FROM coupon WHERE coupon_id='$pass_coupon_id'")->result_array();
foreach ($coupon_array as $row) {
$spec = json_decode($row['spec'], true);
}
$quantity_new = $spec['quantity'] - 1;
$data2 = array(
'spec' => json_encode(array(
'quantity'=> $quantity_new
)));
$this->db->where('coupon_id', $pass_coupon_id);
$this->db->update('coupon', $data2);
You need to overrite only this one field and update whole field in query.
<?php
$pass_coupon_id = $this->pass_coupon_id();
$coupon_array = $this->db->query("SELECT * FROM coupon WHERE coupon_id='$pass_coupon_id'")->result_array();
// i don't know what you're using, but using foreach to extract single row isn't good solution. Look for sth like result_row() maybe.
$coupon = $coupon_array[0];
$spec = json_decode($coupon, true);
$new_quantity = $spec['quantity'] - 1;
$spec['quantity'] = $new_quantity;
$new_spec = json_encode($spec);
$this->db->where('coupon_id', $pass_coupon_id);
$this->db->update('coupon', $new_spec);
Depending on the database, the best solution would be using specific function to ommit updating whole structure - https://stackoverflow.com/a/34987329/2926214

Output data from mysql to array json driving me crazy

im trying to pull out a menu in this json format :
check the output : http://www.alacarta.do/iphone/webservices/restaurants_menu2.php?r=415
The thing is that iterating of the Category plates, it duplicates the plates and then add the corresponding correct ones in each Category. all the time. check the output in the link. first category is TO SHARE. and the plates are ok, but the second category FRIES BAR, will throw again the plates from TO SHARE and then the correct plates in its category
<?
$where = empty($_GET['r'])? NULL : 'id = '. intval($_GET['r']);
$restaurant = $cmp->empresas($where,"nombre ASC")->fetch();
$json = array();
$arraynombre = array();
while($orden = $cmp->platos_tipos_orden("id_empresa = {$restaurant->id}","orden ASC")->foreachrow()):
$tipo = $cmp->platos_tipos("id = {$orden->id_tipo}")->fetch();
while($menu = $cmp->platos_menu("id_tipo = {$orden->id_tipo} AND id_empresa = {$orden->id_empresa}")->foreachrow()):
$p = $cmp->platos_lista("id = {$menu->id_plato}")->fetch();
$pnombre = $p->nombre;
$pid = $p->id;
$pprecio = $p->precio;
$arraynombre1 = array('plato_id'=>$pid,'plato_nombre'=>$pnombre,'precio'=>$pprecio);
if (in_array($arraynombre1['plato_id'], $arraynombre['plato_id'])) continue;
$arraynombre[] = $arraynombre1;
endwhile;
$jsondata = array('tipo'=> utf8_decode($tipo->nombre),'platos' => $arraynombre);
$json[] = $jsondata;
endwhile;
echo json_encode( array("menu"=>$json));
?>
Your issue is probably this line -
$arraynombre[] = $arraynombre1;
as you continually add to the array, not overwrite the previous loops values.
Try adding a key to it that is unique to each loop, ie. $orden->id_tipo -
$arraynombre[$orden->id_tipo][] = $arraynombre1;
Then you would also need to change
$jsondata = array('tipo'=> utf8_decode($tipo->nombre),'platos' => $arraynombre);
to
$jsondata = array('tipo'=> utf8_decode($tipo->nombre),'platos' => $arraynombre[$orden->id_tipo]);
note- it is hard to follow all your code logic, so [$orden->id_tipo] might need to be [$orden->id_empresa] or could be a similar counter var [$x] that you increase on each loop.

2 foreach loop, repeating results

Basically iv getting a list or orders, then a list of items associated with that user.
This is my code
$collection_array = array();
$collection_items_array = array();
foreach($getCollections as $k => $collection){
$collection_array['CustomerAccountID'] = $collection['collection_account_id'];
$collection_array['TotalCount'] = $collection['totalCount'];
// Get order items
$get_order_items = $Collection->getItems($collection['collection_account_id']);
foreach($get_order_items as $i => $items){
$collection_items_array['OrderID'] = $items['order_id'];
$collection_items_array['OrderItemID'] = $items['item_id'];
$cia[] = $collection_items_array;
}
$collection_array['CollectionItems'] = $cia;
$ca[] = $collection_array;
}
but when i echo this out, its showing all the correct results for the results but then it shows the seconds results + the results...

PHP json_encoding datas with parent and child categories

Iam trying with the json_encoding for about two hours but iam not getting the output as required. Actually this is a requirement for the mobile application developer who is asking in the format which i will explain here.The code below is what i have tried:
include_once("class_connection.php");
//Getting the Parent Category
$sqlStr = mysql_query("select catname , id from `category` where `parentid`='0'");
$jsonArray = array();
while ($fetchStr = mysql_fetch_assoc($sqlStr)) {
$jsonArray[] = array("ParentCategory" => $fetchStr["catname"]);
$id = $fetchStr['id'];
//Getting child categories from the above parent
$sqlChildStr = mysql_query("SELECT catname,id,parentid FROM `category` where `parentid`='$id'");
while ($fetchchildStr = mysql_fetch_assoc($sqlChildStr)) {
$jsonArray[] = array("ChildCategory" => $fetchchildStr["catname"]);
}
}
echo json_encode(array("JsonOutput" => $jsonArray)) . "<br />";
The Output is :
"JsonOutput":[{"ParentCategory":"Animals"},{"ChildCategory":"Bear"},{"ChildCategory":"Deer"},{"ChildCategory":"Dolphins"},
{"ParentCategory":"Art"},{"ChildCategory":"Hand Painting"},{"ChildCategory":"Painting"},{"ChildCategory":"3D"},{"ChildCategory":"Abstract"}]}
Here , in the above output the parent category array is empty without its child category array. I want to store all the child category array in its parent category array and finally i have to store both parent and child category into the JsonOutput array so i want the output as
"JsonOutput":[{
"ParentCategory":"Animals" : [{
{"ChildCategory":"Bear"},{"ChildCategory":"Deer"},{"ChildCategory":"Dolphins"}
]}
"ParentCategory":"Arts" : [{
{"ChildCategory":"Hand Painting"},{"ChildCategory":"Painting"},{"ChildCategory":"3D"}, {"ChildCategory":"Abstract"}
]}
]}
You probably need to do this (only the important bits are shown):
$jsonArray = array();
while ($parentCat = mysql_fetch_assoc($sqlStr)) {
$temp = array(
"ParentCategory" => $parentCat["catname"]
);
while ($childCat = mysql_fetch_assoc($sqlChildStr)) {
$temp["ChildCategory"][] = array(
"ChildCategory" => $childCat["catname"]
);
}
$jsonArray[] = $temp;
}
I used a temporary variable for storing and manipulating the parent category. This gets added to the main array at the end of loop.
Please use the following codes, give the index inside the while loop...
$jsonArray = {};
while ($fetchStr = mysql_fetch_assoc($sqlStr)) {
//$jsonArray[] = array("ParentCategory" => $fetchStr["catname"]);
$id = $fetchStr['id'];
//Getting child categories from the above parent
$sqlChildStr = mysql_query("SELECT catname,id,parentid FROM `category` where `parentid`='$id'");
while ($fetchchildStr = mysql_fetch_assoc($sqlChildStr)) {
$jsonArray["ParentCategory"][$fetchStr["catname"]] = array("ChildCategory" => $fetchchildStr["catname"]);
}
}
echo json_encode(array("JsonOutput" => $jsonArray)) . "<br />";

Multidimensional Arrays in PHP

How do i add items into a multidimensional array? Basically i am making an application which calculates what people are buying in a suppermarket and how much of it.
Sue buys 2 tubs of butter and 1.
toothpaste
John buys 1 peach and 1 banana.
I think the array would look something like this
$sue[butter] = array();
$sue[butter][] = 2;
$sue[toothpaste] = array();
$sue[toothpaste][] = 1;
$john[peach] = array();
$john[peach][] = 1;
$john[banana] = array();
$john[banana][] = 1;
My current code can only record the item and the item quantity.
public $items = array();
public function AddItem($product_id)
{
if (array_key_exists($product_id , $this->items))
{
$this->items[$product_id] = $this ->items[$product_id] + 1;
} else {
$this->items[$product_id] = 1;
}
}
I just dont know how to put this inside an array for each person.
Thanks!
Instead of doing this, you might find it easier to encapsulate into a class. For instance, have each person be a class, and then give them attributes.
Once you get into multidimensional arrays, it becomes more difficult to maintain your code.
For instance (this is pseudocode):
class Customer {
//this is an array of FoodItem objects.
private $foodItems[];
// any other methods needed for access here
}
class FoodItem {
//could be a String, or whatever it needs to be
private $itemType;
//the number of that item purchased
private $numPurchased;
}
Hm, maybe I fail to see the multi-dimensionality here?
$sue = array();
$sue['butter'] = 2;
$sue['toothpaste'] = 1;
$john = array();
$john['peach'] = 1;
$john['banana'] = 1;
I think the function you've shown would work with the above.
You dont need to create another array to hold the number of items like you did here:
$sue[butter] = array();
$sue[butter][] = 2;
I think something like this would work:
$customers[sue][butter] = 2;
$customers[sue][toothpaste] = 1;
$customers[john][peach] = 1;
$customers[john][banana] = 1;
This way you create an array of customer names. Then in each customer array you have an array of their products. Then each product holds the number of that product the customer bought.
$data = array();
$data["persons"] = array("Sue","John");
$data["articles"] = array("butter","toothpaste","peach","banana");
$data["carts"] = array();
$data["carts"][0][0] = 2; // sue's 2 butter packets
$data["carts"][0][1] = 1; // sue's 1 tooth paste
$data["carts"][1][2] = 1; // john's peach
$data["carts"][1][3] = 1; // john's banana

Categories