I'm trying to generate a JSON API using PHP to be used as remote server interface for my Android application database.
I managed to generate JSON like this:
{
products: [
{
product_name: "Samsung",
product_category: "phones",
shop_name: "Gadget Store",
user_id: "1",
price: "1999",
date: "2015-04-05",
time: "11:14:44"
},
{
product_name: "Samsung",
product_category: "phones",
shop_name: "IT Store",
user_id: "1",
price: "1899",
date: "2015-04-01",
time: "13:00:00"
},
{
product_name: "Motorola",
product_category: "phones",
shop_name: "IT Store",
user_id: "1",
price: "1499",
date: "2015-04-02",
time: "10:31:29"
}
]
}
But I guess I need a nested JSON which is something like this:
{
products: [
{
product_name: "Samsung",
product_category: "phones",
shops: [
{
shop_name: "Gadget Store",
user_id: "1",
price: "1999",
date: "2015-04-05",
time: "11:14:44"
},
{
shop_name: "IT Store",
user_id: "1",
price: "1899",
date: "2015-04-01",
time: "13:00:00"
}
],
},
{
product_name: "Motorola",
product_category: "phones",
shops: [
shop_name: "IT Store",,
user_id: "1",
price: "199",
date: "2015-04-02",,
time: "10:31:29"
],
}
]
}
How can I achive this result?
The sql query is from 3 different table.
Below is my current code:
class productDB
{
public $product_name = "";
public $product_category = "";
public $shop_name = "";
public $user_id = "";
public $price;
public $date = "";
public $time = "";
function __construct($product_name, $product_category, $shop_name, $user_id, $price, $date, $time)
{
$this->product_name = $product_name;
$this->product_category = $product_category;
$this->shop_name = $shop_name;
$this->user_id = $user_id;
$this->price = $price;
$this->date = $date;
$this->time = $time;
}
class Shop
{
public $shop_name = "";
public $user_id = "";
public $price;
public $date = "";
public $time = "";
function __construct($shop_name, $user_id, $price, $date, $time)
{
$this->shop_name = $shop_name;
$this->user_id = $user_id;
$this->price = $price;
$this->date = $date;
$this->time = $time;
}
}
class product
{
public $product_name = "";
public $product_category = "";
public $shop = "";
function __construct($product_name, $product_category, $shop_name, $user_id, $price, $date, $time)
{
$this->product_name = $product_name;
$this->product_category = $product_category;
$this->shop = new Shop($shop_name, $user_id, $price, $date, $time);
}
}
$query = "SELECT a.product_name, a.product_category,
b.shop_name,
c.user_user_id, c.price, c.date, c.time
FROM price c, item a, shop b
WHERE c.product_product_id = a.product_id AND c.shop_shop_id = b.shop_id";
$product_array = array();
if ($result = $dbc->query($query)) {
while ($obj = $result->fetch_object()) {
$temp_product[] = new ProductDB(
$obj->product_name,
$obj->product_category,
$obj->shop_name,
$obj->user_id,
$obj->price,
$obj->date,
$obj->time);
$product_array = $temp_product;
}
//Give a name to the array
$array_name = 'products';
$product_array = (array($array_name=>$product_array));
$product_object = json_encode($product_array);
echo $product_object;
Here you have a solution which does not require subqueries.
It looks like at least in this example you do not need the ProductDB so we will use directly Product class
To keep the shops in the Product object we need the holder there. We will change $shop into $shops which will hold an array with Shop objects.
Product class:
class Product
{
public $product_name = "";
public $product_category = "";
public $shops = null;
function __construct($product_name, $product_category, $shop_name, $user_id, $price, $date, $time)
{
$this->product_name = $product_name;
$this->product_category = $product_category;
$this->shops = array(new Shop($shop_name, $user_id, $price, $date, $time));
}
public function addShop($shop_name, $user_id, $price, $date, $time)
{
// because $shops is a public property we can check if it still is an array
if (!is_array($this->shops)) {
$this->shops = array();
}
$this->shops[] = new Shop($shop_name, $user_id, $price, $date, $time);
}
}
Ass you can see there is a new function which adds new shops to the array.
Now the part which will group the shops into the products.
$product_array = array();
$currProduct = null;
if ($result = $dbc->query($query)) {
while ($obj = $result->fetch_object()) {
// check if it is a first product or if we have encountered product with different name or category
if ($currProduct === null
|| $currProduct->product_name !== $obj->product_name
|| $currProduct->product_category !== $obj->product_category) {
// create new Product with one position in the shops array
$product = new Product(
$obj->product_name,
$obj->product_category,
$obj->shop_name,
$obj->user_id,
$obj->price,
$obj->date,
$obj->time);
$product_array[] = $product;
// set created product as a currently used
$currProduct = $product;
} else {
// if name and category is the same add shop data to the current product
$currProduct->addShop(
$obj->shop_name,
$obj->user_id,
$obj->price,
$obj->date,
$obj->time);
}
}
$product_array = array('products' => $product_array);
$product_json = json_encode($product_array);
echo $product_json;
}
TO group the data properly it is necessary to sort the products data. So add at the end of the query ORDER BY a.product_name, a.product_category.
That's it :) Let me know how if it worked (if you will use it)
Also if you would like to declare the class properties private and still use json_encode to get the JSON representation of your classes, you can use JsonSerializable interface.
Shop class
class Shop implements \JsonSerializable
{
private $shop_name = "";
private $user_id = "";
private $price;
private $date = "";
private $time = "";
function __construct($shop_name, $user_id, $price, $date, $time)
{
$this->shop_name = $shop_name;
$this->user_id = $user_id;
$this->price = $price;
$this->date = $date;
$this->time = $time;
}
public function JsonSerialize()
{
return get_object_vars($this);
}
}
Product class
class Product implements \JsonSerializable
{
private $product_name = "";
private $product_category = "";
private $shops = null;
function __construct($product_name, $product_category, $shop_name, $user_id, $price, $date, $time)
{
$this->product_name = $product_name;
$this->product_category = $product_category;
$this->shops = array(new Shop($shop_name, $user_id, $price, $date, $time));
}
public function addShop($shop_name, $user_id, $price, $date, $time)
{
$this->shops[] = new Shop($shop_name, $user_id, $price, $date, $time);
}
function getName()
{
return $this->product_name;
}
function getCategory()
{
return $this->product_category;
}
public function JsonSerialize()
{
return get_object_vars($this);
}
}
Main code
[...]
if ($currProduct === null
|| $currProduct->getName() !== $obj->product_name
|| $currProduct->getCategory() !== $obj->product_category) {
[...]
Have fun :)
To keep a consistent JSON structure, the second part would look like this:
{
product_name: "Motorola",
product_category: "phones",
shops: [
shop_name: "IT Store",
user_id: "1",
price: "1499",
date: "2015-04-02",
time: "10:31:29"
]
}
How about something like this:
$queryStr_products = "Select * FROM item";
$queryStr_price = "Select b.shop_name, c.user_user_id, c.price, c.date, c.time FROM price c, shop b WHERE b.shop_id = c.product_product_id and c.product_product_id =";
$product_array = array();
if ($result = $dbc->query($queryStr_products)) {
//Iterate over all products returned
while ($obj = $result->fetch_object()) {
$product_array[] = array (
'product_name' => $obj->product_name,
'product_category' => $obj->product_category,
'shops' => getPricesForProducts($obj->product_id)
);
}
$result->close();
}
echo json_encode(array('products'=>$product_array));
/**
* For clarity purposes
* This returns an array of all product prices for a particular productID
*/
function getPricesForProducts ($productID) {
//You may need to get a new DB connection
if ($result = $dbc2->query($queryStr_price.$productID)) {
$price_array = array();
while($obj = $result->fetch_object()) {
$price_array[] = array (
'shop_name' => $obj->b.shop_name,
'user_id' => $obj->c.user_user.id,
'price' => $obj->c.price,
'date' => $obj->c.date,
'time' => $obj->c.time,
);
}
$result->close();
return $price_array;
} else {
//Maybe you want to set shop_name to "No Prices Found" and user_id = 0;
return array();
}
}
Related
I have made function to display all my privileges against the menu
My Controller code below:
<?php
class PrivilegesController extends Controller
{
public function getAllPrivileges()
{
$privileges = DB::table('prev_definition')->orderBy('id', 'asc')->get();
$privileges = $this->build_heirarchy($privileges);
$resultArray = ['status' => true, 'message' => 'Privileges found!', 'data' => $privileges];
return json_encode($resultArray);
}
public function build_heirarchy($result_set, $parent_id = 0)
{
$rs = array();
foreach ($result_set as $row) {
$row['is_checked'] = 1; // here is error
if ($row['parent_id'] == $parent_id) {
$children = $this->build_heirarchy($result_set, $row['id']);
if ($children) {
if ($children[0]['type'] == 'menu') {
$type = 'submenu';
} else {
$type = 'permission';
}
$row[$type] = $children;
}
$rs[] = $row;
}
}
return $rs;
}
}
?>
But I'm getting error of Cannot use object of type stdClass as array I'm so confused how I can make it happen and working
your help will be highly appreciated!
{
"data": [
{
"created_at": "2019-05-20 15:48:34",
"deletedAt": null,
"display_group": "patient",
"icon": "NULL",
"id": 297,
"isDeleted": null,
"is_checked": 1,
"parent_id": 0,
"priv_key": "can_access_patient",
"priv_title": "Patient",
"type": "menu",
"updated_at": "2019-05-20 15:48:34"
}
],
"message": "Privileges found!",
"status": true
}
class PrivilegesController extends Controller
{
public function getAllPrivileges()
{
$privileges = DB::table('prev_definition')->orderBy('id', 'asc')->get();
$privileges = $this->build_heirarchy($privileges);
$resultArray = ['status' => true, 'message' => 'Privileges found!', 'data' => $privileges];
return json_encode($resultArray);
}
function build_heirarchy($result_set, $parent_id = 0)
{
$rs = array();
foreach ($result_set as $row) {
$row->is_checked = 1; // here is error
if ($row->parent_id == $parent_id) {
$children = $this->build_heirarchy($result_set, $row->id);
if ($children) {
if ($children[0]->type == 'menu') {
$type = 'submenu';
} else {
$type = 'permission';
}
$row->{$type} = $children; // keys to object can only set using curly braces if variable
}
$rs[] = $row;
}
}
return $rs;
}
}
This is my final controller code and i have also shared the response with you can look into this and can let me know if there is any more changges
As per your suggestions and comments I modified your code, once check and let me know.
class PrivilegesController extends Controller
{
public function getAllPrivileges()
{
$privileges = DB::table('prev_definition')->orderBy('id', 'asc')->get();
// add below line, keep your old code as it is and check
$privileges = json_decode(json_encode($privileges), true);
$privileges = $this->build_heirarchy($privileges);
$resultArray = ['status' => true, 'message' => 'Privileges found!', 'data' => $privileges];
return json_encode($resultArray);
}
public function build_heirarchy($result_set, $parent_id = 0)
{
$rs = array();
foreach ($result_set as $row) {
$row['is_checked'] = 1; // here is error
if ($row['parent_id'] == $parent_id) {
$children = $this->build_heirarchy($result_set, $row['id']);
if ($children) {
if ($children[0]['type'] == 'menu') {
$type = 'submenu';
} else {
$type = 'permission';
}
$row[$type] = $children;
}
$rs[] = $row;
}
}
return $rs;
}
}
EDIT
There is only record with parent id 0, so it will create only one parent record, and recursively it will have appended child data. Check this.
Now for parent id 1 it has 2 records in screenshot, so two elements will appended inside parent single most element.
Now for parent id 2 it has 4 records in screenshot, so 4 elements will be appended inside element with id 2.
This will go on inside to inside of every element considering parent
id.
Subsequently all data will be appended to every parent of it. So index is only one and data is appended recursively to its every relevant parent.
I hope I am clear.
if ($children)
{
if($children[0]->type=='menu')
$type = 'submenu';
else
$type = 'permission';
$row[$type] = $children;
}
I am generating a xlsx file with PHPspreadshet and it always gives me an empty file (0kb) when it has more than 16 rows. I already tried to search for erros etc. and found nothing. It just depends on the row.
The Spreadsheet (Html for testing):
And when I switch following lines:
$this->sheet->setCellValue("A16", "Besetzt");
To
$this->sheet->setCellValue("A17", "Besetzt");
The generator (execute() is the entry point):
class ExcelOperation extends AbstractOperation
{
private function addWork($cell, $name = "", $phone = ""){
if($cell != null){
$richText = new \PhpOffice\PhpSpreadsheet\RichText\RichText();
$boldText = $richText->createText($name);
//$boldText->getFont()->setBold(true);
$richText->createText("\n".$phone);
$this->sheet->getCell($cell)->setValue($richText);
$this->sheet->getStyle($cell)->getAlignment()->setWrapText(true);
$this->sheet->getStyle($cell)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
}
}
public function execute(WebRequest $wreq, WebResponse $wres){
$eventId = $wreq->getParameter();
$userId = "1839357067871549236";
$calendar = $this->getCalendar($userId, $eventId);
$eventStatistics = $this->getEventStatistics($eventId);
//All Positions
$this->renderPositionData($calendar);
//$this->renderCurrentStatus($eventStatistics);
$this->formatColumn("A");
$this->formatColumn("B");
$this->formatColumn("C");
$this->formatColumn("D");
//$writer = new Xlsx($this->spreadsheet);
$writer = new Html($this->spreadsheet);
$wres->success(true);
$wres->set("filename", "Schichtplan.html");
$wres->set("file", $writer->save('php://output'));
}
private function addFullBorder($from, $to){
/*$styleArray = array(
'borders' => array(
'outline' => array(
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK,
'color' => array('argb' => PhpOffice\PhpSpreadsheet\Style\Color::COLOR_BLACK),
),
),
);
$this->sheet ->getStyle($from.':'.$to)->applyFromArray($styleArray);*/
}
private function renderCurrentStatus($statistics){
$this->sheet->setCellValue("F2", "Stand");
$this->sheet->mergeCells('F2:G2');
$this->sheet->getStyle("F2")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
$this->sheet->getStyle("F2")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID);
$this->sheet->getStyle("F2")->getFill()->getStartColor()->setRGB("A4DDF5");
$this->sheet->getStyle("F2")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
$frei = $statistics["gesamt"]-($statistics["warten"]+$statistics["besetzt"]);
$this->sheet->setCellValue("F2", "Frei");
$this->sheet->setCellValue("G2", $frei);
$this->sheet->setCellValue("F4", "Besetzt");
$this->sheet->setCellValue("G4", $statistics["besetzt"]);
$this->sheet->setCellValue("F6", "Wartend");
$this->sheet->setCellValue("G6", $statistics["warten"]);
$this->sheet->setCellValue("F8", "Gesamt");
$this->sheet->setCellValue("G8", $statistics["gesamt"]);
$this->addFullBorder("F2", "G8");
}
private function renderPositionData($calendar){
foreach($calendar as $positionId => $position){
$positionName = $position["position"]["alle_positionen_description"];
preg_match('/Pos\. [0-9]+/', $positionName, $matches);
$positionEndCell = null;
$actualCol = $this->positionCount%$this->positionsPerLine;
if(isset($matches[0])){
$shortPositionName = $matches[0];
}else{
$shortPositionName = $positionName;
}
if($actualCol <5){
$cell = $this->getCell($actualCol, $this->actualRowPerPosition);
//var_dump($cell);
//For Position header
$this->actualRowPerPosition[$actualCol] += 1;
$this->addPositionHeader($cell, $shortPositionName);
$positionStartCell = $cell;
//All shifts within this job
foreach($position["jobs"] as $job){
//For Each Shift in Position
$cell = $this->getCell($actualCol, $this->actualRowPerPosition);
//$cell = "A17";
//var_dump($cell);
$this->sheet->setCellValue("A17", "Besetzt");
$formattedDateFrom = $this->dbDateToTime($job["job"]["alle_schichten_start"]);
$formattedDateTo = $this->dbDateToTime($job["job"]["alle_schichten_ende"]);
$this->addShiftHeader($cell, $formattedDateFrom." - ".$formattedDateTo);
$this->actualRowPerPosition[$actualCol] = 18;
$positionEndCell = $cell;
foreach($job["workers"] as $worker){
$fullName = $worker["firstname"]." ".$worker["secondname"];
$phone = "+43";
$cell = $this->getCell($actualCol, $this->actualRowPerPosition);
$this->addWork($cell, $fullName, $phone);
//$this->actualRowPerPosition[$actualCol] += 1;
$positionEndCell = $cell;
}
}
if($positionEndCell == null){
$positionEndCell = $positionStartCell;
}
$this->addFullBorder($positionStartCell, $positionEndCell);
$this->positionCount++;
}
}
}
private function formatColumn($columnName){
$this->sheet->getColumnDimension($columnName)->setWidth(35);
}
private function dbDateToTime(string $dateTime){
$date = new \DateTime($dateTime);
$formattedDateFrom = $date->format('H:i');
return $formattedDateFrom;
}
private function getCell($actualCol, $actualRowPerPosition){
$actualRow = $actualRowPerPosition[$actualCol]+1;
$actualColName = $this->getColName($actualCol);
$cell = $actualColName.$actualRow;
$this->sheet->getRowDimension($actualRow)->setRowHeight(30);
return $cell;
}
private function addPositionHeader($cell, $positionName){
$this->sheet->setCellValue($cell, $positionName);
//Font Color
$this->sheet->getStyle($cell)->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
$this->sheet->getStyle($cell)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
//Background Color
$this->sheet->getStyle($cell)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID);
$this->sheet->getStyle($cell)->getFill()->getStartColor()->setRGB("A4DDF5");
}
private function addShiftHeader($cell, $shiftText){
$this->sheet->setCellValue($cell, $shiftText);
$this->sheet->getStyle($cell)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
}
private function getColName($colId){
$cols = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N"];
return $cols[$colId];
}
private function getCalendar($userId, $eventId){
$dbManager = new DbManager();
$jobs = $dbManager->getAdminCalendarForUser($eventId, $userId);
$calendar = $this->generateCalendarArray($jobs);
return $calendar;
}
private function getEventStatistics($eventId){
$dbManager = new DbManager();
$eventStatistics = $dbManager->getEventStatistics($eventId);
return $eventStatistics;
}
private function generateCalendarArray($jobs){
$dbManager = new DbManager();
$calendar = [];
foreach ($jobs as $job) {
if(!isset($calendar[$job["alle_positionen_id"]])){
$jobFieldsWithValues = $this->getJobFieldsWithValues($dbManager, $job["alle_positionen_id"]);
$job["needs_approval"] = $job["needs_approval"] ? true : false;
$calendar[$job["alle_positionen_id"]] =
[
"position" =>$job,
"jobFieldsWithValues"=> $jobFieldsWithValues,
"jobs" => [],
"positionPermission"=>$job["positionPermission"]
];
}
//Check if position has shift
if($job["alle_schichten_id"] != null){
//Check if job in this shift (falsely defined as job) exists
if(!isset($calendar[$job["alle_positionen_id"]]["jobs"][$job["alle_schichten_id"]])){
$calendar[$job["alle_positionen_id"]]["jobs"][$job["alle_schichten_id"]] = [
"job"=>$job,
"workers"=>[]
];
}
if($job["Email"] != null){
$jobDef = [
"email"=>$job["Email"],
"approved"=>$job["Approved"],
"userId"=>$job["id"]."",
"firstname"=>$job["Vorname"],
"secondname"=>$job["Nachname"]
];
array_push($calendar[$job["alle_positionen_id"]]["jobs"][$job["alle_schichten_id"]]["workers"], $jobDef);
}
}
}
return $calendar;
}
private function getJobFieldsWithValues(DbManager $dbManager, int $positionId) : array{
$jobFieldsWithValues = [];
$jobFields = $dbManager->getJobFieldsWithValues($positionId);
foreach ($jobFields as $jobField) {
if(isset($jobFieldsWithValues[$jobField["id"]])){
array_push($jobFieldsWithValues[$jobField["id"]]["values"], ["data-value"=>$jobField["value"], "value"=>$jobField["value"]]);
}else{
$jobFieldsWithValues[$jobField["id"]] = [
"id"=>$jobField["id"],
"fieldBaseType"=>$jobField["fieldDataType"],
"name"=>$jobField["Bezeichnung"],
"description"=>$jobField["description"],
"values"=>[]];
array_push($jobFieldsWithValues[$jobField["id"]]["values"], ["data-value"=>$jobField["value"], "value"=>$jobField["value"]]);
}
}
return $jobFieldsWithValues;
}
public function __construct() {
$this->spreadsheet = new Spreadsheet();
$this->sheet = $this->spreadsheet->getActiveSheet();
$this->positionsPerLine = 4;
$this->actualRowPerPosition = [0,0,0,0];
$this->positionCount = 0;
$this->colors = [
"black"=>\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_BLACK
];
}
}
It generates an empty file.
I am working on a project that gets an array of integers from the api and prints them on the screen. The problem here is, POSTMAN shows that there is data in json format with no errors as shown in the figure but react js says there's no data.
The api code, the sizes in $attributes are there just to see that react takes those but doesn't take others that come form the database (Click To See the code)
This is the api code.
public function __construct()
{
$this->load->database();
}
public function getAllProducts()
{
$query = $this->db->get('products');
return $query->result_array();
}
private function cutifyProduct($productResult,$isSingle=false){
foreach($productResult as $key => $product){
$productId = $product['id'];
$mediaQuery = $this->db->get_where('media',array('productId'=>$productId));
$categoryQuery = $this->db->get_where('categories',array('id'=>$product['categoryId']));
$thisProductCategory = $categoryQuery->result_array()[0];
$productResult[$key]['categoryTitle'] = $thisProductCategory['name'];
if($isSingle){
//for breadcrumb
$breadcrumb = [];
$breadcrumb[] = $thisProductCategory;
while($thisProductCategory['parentId']!=0){
$categoryQuery = $this->db->get_where('categories',array('id'=>$thisProductCategory['parentId']));
$thisProductCategory = $categoryQuery->result_array()[0];
$breadcrumb[] = $thisProductCategory;
};
$productResult[$key]['breadcrumb'] = $breadcrumb;
//for product attributes
$attributes = [];
$tempSizeAttribute = array();
$tempColorAttribute = [];
$tempStorageAttribute = [];
$tempRamAttribute = [];
$attributesQuery = $this->db->get_where('attributes',array('productId'=>$productId));
$thisProductAttributes = $attributesQuery->result_array();
$attributes['size'] = array(
"sizeType"=>"UK",
"sizes"=>array(1,2,3),
);
foreach($thisProductAttributes as $productAttribute){
if($productAttribute['title']=="size"){
//$attributes['size']['sizes'][] = (int) $productAttribute['name'];
$tempSizeAttribute[]=(int) $productAttribute['name'];
}elseif($productAttribute['title']=="color"){
$tempColorAttribute[] = array(
"productId"=>explode("|",$productAttribute['name'])[0],
"name"=>explode("|",$productAttribute['name'])[1],
);
}
}
$attributes['size']['sizes'] =array_merge($attributes['size']['sizes'],$tempSizeAttribute);
$productResult[$key]['attributes'] = $attributes;
//for vendor information
$vendorInfo = [];
$vendorQuery = $this->db->get_where('vendors',array('id'=>$product['vendorId']));
$vendorResult = $vendorQuery->result_array();
$productResult[$key]['vendorDetails'] = $vendorResult;
}
$productResult[$key]['media'] = $mediaQuery->result_array();
$productResult[$key]['link'] = "/product/".$productResult[$key]['slug'];
if($productResult[$key]['discountPercent']=="0.00" || $productResult[$key]['discountPercent']==0 || $productResult[$key]['discountPercent']=="0" || $productResult[$key]['discountPercent']=="0.0"){
$productResult[$key]['price'] = array(
"current"=> $productResult[$key]['price'],
);
}else{
$productResult[$key]['price'] = array(
"current"=> $productResult[$key]['price'] - (($productResult[$key]['discountPercent']*$productResult[$key]['price'])/100),
"previous"=> $productResult[$key]['price'],
);
}
foreach($productResult[$key]['media'] as $mediaKey => $media){
if($isSingle){
if($media['isPrimary']=="1" || $media['isPrimary']==1 ){
if(substr( $media['url'], 0, 4 ) != "http"){
$productResult[$key]['image']= "https://admin.ratomatoshop.com/media/medium/".$media['url'];
}
}
if(substr( $media['url'], 0, 4 ) != "http"){
$productResult[$key]['images']['medium'][]= "https://admin.ratomatoshop.com/media/medium/".$media['url'];
$productResult[$key]['images']['original'][]= "https://admin.ratomatoshop.com/media/original/".$media['url'];
}else{
$productResult[$key]['images']['original'][]=$media['url'];
}
}else{
if($media['isPrimary']=="1" || $media['isPrimary']==1 ){
if(substr( $media['url'], 0, 4 ) != "http"){
$productResult[$key]['image']= "https://admin.ratomatoshop.com/media/small/".$media['url'];
}
}
}
}
}
return $productResult;
}
public function getLatestProducts($noOfProducts)
{
$this->db->order_by('id', 'DESC');
$this->db->limit($noOfProducts);
$query = $this->db->get('products');
$productResult = $query->result_array();
return $this->cutifyProduct($productResult);
}
public function getOnSaleProducts($noOfProducts)
{
$this->db->order_by('discountPercent', 'DESC');
$this->db->limit($noOfProducts);
$query = $this->db->get('products');
$productResult = $query->result_array();
return $this->cutifyProduct($productResult);
}
public function getTopRatedProducts($noOfProducts)
{
$this->db->order_by('rating', 'DESC');
$this->db->limit($noOfProducts);
$query = $this->db->get('products');
$productResult = $query->result_array();
return $this->cutifyProduct($productResult);
}
public function getProductData($productSlug)
{
$query = $this->db->get_where('products',array('slug'=>$productSlug));
$productResult = $query->result_array();
return $this->cutifyProduct($productResult,true);
}
public function getFeaturedProducts($noOfProducts)
{
$this->db->order_by('id', 'DESC');
$this->db->limit($noOfProducts);
$query = $this->db->get('featuredproducts');
$results = $query->result_array();
$products = [];
foreach($results as $result ){
$products[] = $this->getWhere('id',$result['productId']);
}
return $this->cutifyProduct($products);
}
public function getSpecialProducts($noOfProducts)
{
$this->db->order_by('id', 'DESC');
$this->db->limit($noOfProducts);
$query = $this->db->get('specialproducts');
$results = $query->result_array();
$products = [];
foreach($results as $result ){
$product = $this->getWhere('id',$result['productId'])[0];
$product['dateEnd'] = $result['dateEnd'];
$product['discountPercent'] = $result['discountPercent'];
$products[] = $product;
}
return $this->cutifyProduct($products);
}
public function newProduct($productData)
{
return $this->db->insert('products',$productData);
}
public function isProduct($productId){
$product = $this->getWhere('id',$productId);
if($product!=null && is_array($product) && count($product)>0){
return true;
}else{
return false;
}
}
public function getWhere($key,$value){
$query = $this->db->get_where('products',array($key=>$value));
return $query->result_array();
}
}
The postman response from the api (Click To See the code)
This is the post man response
"attributes": {
"size": {
"sizeType": "UK",
"sizes": [
1,
2,
3,
36,
37,
38,
39,
40
]
}
},
The json data that react gets. (Click To See the code)
This is the react's console log:
"attributes": {
"size": {
"sizeType": "UK",
"sizes": [
1,
2,
3,
]
}
},
Im trying to programmatically create an order. I created a model with the following structure:
<?php
class Pricebinc_App_Model_OrderCreate extends Mage_Core_Model_Abstract
{
const CUSTOMER_RANDOM = null;
protected $_shippingMethod = 'freeshipping_freeshipping';
protected $_paymentMethod = 'cashondelivery';
protected $_subTotal = 0;
protected $_order;
protected $_storeId;
public function setShippingMethod($methodName)
{
$this->_shippingMethod = $methodName;
}
public function setPaymentMethod($methodName)
{
$this->_paymentMethod = $methodName;
}
public function setCustomer($customer)
{
if ($customer instanceof Mage_Customer_Model_Customer) {
$this->_customer = $customer;
}
if (is_numeric($customer)) {
$this->_customer = Mage::getModel('customer/customer')->load($customer);
} else if ($customer === self::CUSTOMER_RANDOM) {
$customers = Mage::getResourceModel('customer/customer_collection');
$customers
->getSelect()
->limit(1)
->order('RAND()');
$id = $customers->getFirstItem()->getId();
$this->_customer = Mage::getModel('customer/customer')->load($id);
}
}
public function createOrder($products)
{
if (!($this->_customer instanceof Mage_Customer_Model_Customer)) {
$this->setCustomer(self::CUSTOMER_RANDOM);
}
$transaction = Mage::getModel('core/resource_transaction');
$this->_storeId = Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
$reservedOrderId = Mage::getSingleton('eav/config')
->getEntityType('order')
->fetchNewIncrementId($this->_storeId);
$currencyCode = Mage::app()->getBaseCurrencyCode();
$this->_order = Mage::getModel('sales/order')
->setIncrementId($reservedOrderId)
->setStoreId($this->_storeId)
->setQuoteId(0)
->setGlobalCurrencyCode($currencyCode)
->setBaseCurrencyCode($currencyCode)
->setStoreCurrencyCode($currencyCode)
->setOrderCurrencyCode($currencyCode);
$this->_order->setCustomerEmail($this->_customer->getEmail())
->setCustomerFirstname($this->_customer->getFirstname())
->setCustomerLastname($this->_customer->getLastname())
->setCustomerGroupId($this->_customer->getGroupId())
->setCustomerIsGuest(0)
->setCustomer($this->_customer);
$billing = $this->_customer->getDefaultBillingAddress();
$billingAddress = Mage::getModel('sales/order_address')
->setStoreId($this->_storeId)
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_BILLING)
->setCustomerId($this->_customer->getId())
->setCustomerAddressId($this->_customer->getDefaultBilling())
->setCustomerAddress_id($billing->getEntityId())
->setPrefix($billing->getPrefix())
->setFirstname($billing->getFirstname())
->setMiddlename($billing->getMiddlename())
->setLastname($billing->getLastname())
->setSuffix($billing->getSuffix())
->setCompany($billing->getCompany())
->setStreet($billing->getStreet())
->setCity($billing->getCity())
->setCountry_id($billing->getCountryId())
->setRegion($billing->getRegion())
->setRegion_id($billing->getRegionId())
->setPostcode($billing->getPostcode())
->setTelephone($billing->getTelephone())
->setFax($billing->getFax());
$this->_order->setBillingAddress($billingAddress);
$shipping = $this->_customer->getDefaultShippingAddress();
$shippingAddress = Mage::getModel('sales/order_address')
->setStoreId($this->_storeId)
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_SHIPPING)
->setCustomerId($this->_customer->getId())
->setCustomerAddressId($this->_customer->getDefaultShipping())
->setCustomer_address_id($shipping->getEntityId())
->setPrefix($shipping->getPrefix())
->setFirstname($shipping->getFirstname())
->setMiddlename($shipping->getMiddlename())
->setLastname($shipping->getLastname())
->setSuffix($shipping->getSuffix())
->setCompany($shipping->getCompany())
->setStreet($shipping->getStreet())
->setCity($shipping->getCity())
->setCountry_id($shipping->getCountryId())
->setRegion($shipping->getRegion())
->setRegion_id($shipping->getRegionId())
->setPostcode($shipping->getPostcode())
->setTelephone($shipping->getTelephone())
->setFax($shipping->getFax());
$this->_order->setShippingAddress($shippingAddress)
->setShippingMethod($this->_shippingMethod);
$orderPayment = Mage::getModel('sales/order_payment')
->setStoreId($this->_storeId)
->setCustomerPaymentId(0)
->setMethod($this->_paymentMethod)
->setPoNumber(' – ');
$this->_order->setPayment($orderPayment);
$this->_addProducts($products);
$this->_order->setSubtotal($this->_subTotal)
->setBaseSubtotal($this->_subTotal)
->setGrandTotal($this->_subTotal)
->setBaseGrandTotal($this->_subTotal);
$transaction->addObject($this->_order);
$transaction->addCommitCallback(array($this->_order, 'place'));
$transaction->addCommitCallback(array($this->_order, 'save'));
$transaction->save();
}
protected function _addProducts($products)
{
$this->_subTotal = 0;
foreach ($products as $productRequest) {
if ($productRequest['product'] == 'rand') {
$productsCollection = Mage::getResourceModel('catalog/product_collection');
$productsCollection->addFieldToFilter('type_id', 'simple');
Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($productsCollection);
$productsCollection->getSelect()
->order('RAND()')
->limit(rand($productRequest['min'], $productRequest['max']));
foreach ($productsCollection as $product) {
$this->_addProduct(array(
'product' => $product->getId(),
'qty' => rand(1, 2)
));
}
} else {
$this->_addProduct($productRequest);
}
}
}
protected function _addProduct($requestData)
{
$request = new Varien_Object();
$request->setData($requestData);
$product = Mage::getModel('catalog/product')->load($request['product']);
$cartCandidates = $product->getTypeInstance(true)
->prepareForCartAdvanced($request, $product);
if (is_string($cartCandidates)) {
throw new Exception($cartCandidates);
}
if (!is_array($cartCandidates)) {
$cartCandidates = array($cartCandidates);
}
$parentItem = null;
$errors = array();
$items = array();
foreach ($cartCandidates as $candidate) {
$item = $this->_productToOrderItem($candidate, $candidate->getCartQty());
$items[] = $item;
/**
* As parent item we should always use the item of first added product
*/
if (!$parentItem) {
$parentItem = $item;
}
if ($parentItem && $candidate->getParentProductId()) {
$item->setParentItem($parentItem);
}
/**
* We specify qty after we know about parent (for stock)
*/
$item->setQty($item->getQty() + $candidate->getCartQty());
// collect errors instead of throwing first one
if ($item->getHasError()) {
$message = $item->getMessage();
if (!in_array($message, $errors)) { // filter duplicate messages
$errors[] = $message;
}
}
}
if (!empty($errors)) {
Mage::throwException(implode("\n", $errors));
}
foreach ($items as $item) {
$this->_order->addItem($item);
}
return $items;
}
function _productToOrderItem(Mage_Catalog_Model_Product $product, $qty = 1)
{
$rowTotal = $product->getFinalPrice() * $qty;
$options = $product->getCustomOptions();
$optionsByCode = array();
foreach ($options as $option) {
$quoteOption = Mage::getModel('sales/quote_item_option')->setData($option->getData())
->setProduct($option->getProduct());
$optionsByCode[$quoteOption->getCode()] = $quoteOption;
}
$product->setCustomOptions($optionsByCode);
$options = $product->getTypeInstance(true)->getOrderOptions($product);
$orderItem = Mage::getModel('sales/order_item')
->setStoreId($this->_storeId)
->setQuoteItemId(0)
->setQuoteParentItemId(NULL)
->setProductId($product->getId())
->setProductType($product->getTypeId())
->setQtyBackordered(NULL)
->setTotalQtyOrdered($product['rqty'])
->setQtyOrdered($product['qty'])
->setName($product->getName())
->setSku($product->getSku())
->setPrice($product->getFinalPrice())
->setBasePrice($product->getFinalPrice())
->setOriginalPrice($product->getFinalPrice())
->setRowTotal($rowTotal)
->setBaseRowTotal($rowTotal)
->setWeeeTaxApplied(serialize(array()))
->setBaseWeeeTaxDisposition(0)
->setWeeeTaxDisposition(0)
->setBaseWeeeTaxRowDisposition(0)
->setWeeeTaxRowDisposition(0)
->setBaseWeeeTaxAppliedAmount(0)
->setBaseWeeeTaxAppliedRowAmount(0)
->setWeeeTaxAppliedAmount(0)
->setWeeeTaxAppliedRowAmount(0)
->setProductOptions($options);
$this->_subTotal += $rowTotal;
return $orderItem;
}
}
Then I include the following statement in the controller:
$orderGenerator = Mage::getModel('app/ordercreate');
$orderGenerator->createOrder(array(
array(
'product' => 24, //product id
'qty' => 1
)
));
But I constantly receive error 500.
including Zend_Debug::dump($orderGenerator); creates the following output.
object(Pricebinc_App_Model_OrderCreate)#230 (21) {
["_shippingMethod":protected] => string(25) "freeshipping_freeshipping"
["_paymentMethod":protected] => string(14) "cashondelivery"
["_customer":protected] => NULL
["_subTotal":protected] => int(0)
["_order":protected] => NULL
["_storeId":protected] => NULL
["_eventPrefix":protected] => string(13) "core_abstract"
["_eventObject":protected] => string(6) "object"
["_resourceName":protected] => string(15) "app/ordercreate"
["_resource":protected] => NULL
["_resourceCollectionName":protected] => string(26) "app/ordercreate_collection"
["_cacheTag":protected] => bool(false)
["_dataSaveAllowed":protected] => bool(true)
["_isObjectNew":protected] => NULL
["_data":protected] => array(0) {
}
["_hasDataChanges":protected] => bool(false)
["_origData":protected] => NULL
["_idFieldName":protected] => NULL
["_isDeleted":protected] => bool(false)
["_oldFieldsMap":protected] => array(0) {
}
["_syncFieldsMap":protected] => array(0) {
}
}
I took that code from amasty https://blog.amasty.com/creating-magento-order-programmatically/
UPDATE-------------------------------------------------------------------
current errors display customer is not set. example are Fatal error: Call to a member function getEmail() on a non-object in C:\Zend\Apache2\htdocs\company\app\code\community\Pricebinc\App\Model\OrderCreate.php on line 56 ->$this->_order->setCustomerEmail($this->_customer->getEmail())
finally this is the code if you need to create an order programmatically in magento 1.9.
<?php
class NameApp_App_Model_OrderCreate extends Mage_Core_Model_Abstract
{
const CUSTOMER_RANDOM = null;
protected $_shippingMethod = 'freeshipping_freeshipping';
protected $_paymentMethod = 'cashondelivery';
protected $_subTotal = 0;
protected $_order;
protected $_storeId = '0';
public function _construct()
{
parent::_construct();
$this->_init('app/ordercreate');
}
public function setShippingMethod($methodName)
{
$this->_shippingMethod = $methodName;
}
public function setPaymentMethod($methodName)
{
$this->_paymentMethod = $methodName;
}
public function createOrder($products)
{
$transaction = Mage::getModel('core/resource_transaction');
$this->_storeId = Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
$this->_customer = Mage::getSingleton('customer/session')->getCustomer();
$reservedOrderId = Mage::getSingleton('eav/config')
->getEntityType('order')
->fetchNewIncrementId($this->_storeId);
$currencyCode = Mage::app()->getBaseCurrencyCode();
$this->_order = Mage::getModel('sales/order')
->setIncrementId($reservedOrderId)
->setStoreId($this->_storeId)
->setQuoteId(0)
->setGlobalCurrencyCode($currencyCode)
->setBaseCurrencyCode($currencyCode)
->setStoreCurrencyCode($currencyCode)
->setOrderCurrencyCode($currencyCode);
$this->_order->setCustomerEmail($this->_customer->getEmail())
->setCustomerFirstname($this->_customer->getFirstname())
->setCustomerLastname($this->_customer->getLastname())
->setCustomerGroupId($this->_customer->getGroupId())
->setCustomerIsGuest(0)
->setCustomer($this->_customer);
$billing = $this->_customer->getDefaultBillingAddress();
$billingAddress = Mage::getModel('sales/order_address')
->setStoreId($this->_storeId)
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_BILLING)
->setCustomerId($this->_customer->getId())
->setCustomerAddressId($this->_customer->getDefaultBilling())
->setCustomerAddress_id($billing->getEntityId())
->setPrefix($billing->getPrefix())
->setFirstname($billing->getFirstname())
->setMiddlename($billing->getMiddlename())
->setLastname($billing->getLastname())
->setSuffix($billing->getSuffix())
->setCompany($billing->getCompany())
->setStreet($billing->getStreet())
->setCity($billing->getCity())
->setCountry_id($billing->getCountryId())
->setRegion($billing->getRegion())
->setRegion_id($billing->getRegionId())
->setPostcode($billing->getPostcode())
->setTelephone($billing->getTelephone())
->setFax($billing->getFax());
$this->_order->setBillingAddress($billingAddress);
$shipping = $this->_customer->getDefaultShippingAddress();
$shippingAddress = Mage::getModel('sales/order_address')
->setStoreId($this->_storeId)
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_SHIPPING)
->setCustomerId($this->_customer->getId())
->setCustomerAddressId($this->_customer->getDefaultShipping())
->setCustomer_address_id($shipping->getEntityId())
->setPrefix($shipping->getPrefix())
->setFirstname($shipping->getFirstname())
->setMiddlename($shipping->getMiddlename())
->setLastname($shipping->getLastname())
->setSuffix($shipping->getSuffix())
->setCompany($shipping->getCompany())
->setStreet($shipping->getStreet())
->setCity($shipping->getCity())
->setCountry_id($shipping->getCountryId())
->setRegion($shipping->getRegion())
->setRegion_id($shipping->getRegionId())
->setPostcode($shipping->getPostcode())
->setTelephone($shipping->getTelephone())
->setFax($shipping->getFax());
$this->_order->setShippingAddress($shippingAddress)
->setShippingMethod($this->_shippingMethod);
$orderPayment = Mage::getModel('sales/order_payment')
->setStoreId($this->_storeId)
->setCustomerPaymentId(0)
->setMethod($this->_paymentMethod)
->setPoNumber(' – ');
$this->_order->setPayment($orderPayment);
$this->_addProducts($products);
$this->_order->setSubtotal($this->_subTotal)
->setBaseSubtotal($this->_subTotal)
->setGrandTotal($this->_subTotal)
->setBaseGrandTotal($this->_subTotal);
$transaction->addObject($this->_order);
$transaction->addCommitCallback(array($this->_order, 'place'));
$transaction->addCommitCallback(array($this->_order, 'save'));
$transaction->save();
}
protected function _addProducts($products)
{
$this->_subTotal = 0;
foreach ($products as $productRequest) {
if ($productRequest['product'] == 'rand') {
$productsCollection = Mage::getResourceModel('catalog/product_collection');
$productsCollection->addFieldToFilter('type_id', 'simple');
Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($productsCollection);
$productsCollection->getSelect()
->order('RAND()')
->limit(rand($productRequest['min'], $productRequest['max']));
foreach ($productsCollection as $product) {
$this->_addProduct(array(
'product' => $product->getId(),
'qty' => rand(1, 2)
));
}
} else {
$this->_addProduct($productRequest);
}
}
}
protected function _addProduct($requestData)
{
$request = new Varien_Object();
$request->setData($requestData);
$product = Mage::getModel('catalog/product')->load($request['product']);
$cartCandidates = $product->getTypeInstance(true)
->prepareForCartAdvanced($request, $product);
if (is_string($cartCandidates)) {
throw new Exception($cartCandidates);
}
if (!is_array($cartCandidates)) {
$cartCandidates = array($cartCandidates);
}
$parentItem = null;
$errors = array();
$items = array();
foreach ($cartCandidates as $candidate) {
$item = $this->_productToOrderItem($candidate, $candidate->getCartQty());
$items[] = $item;
/**
* As parent item we should always use the item of first added product
*/
if (!$parentItem) {
$parentItem = $item;
}
if ($parentItem && $candidate->getParentProductId()) {
$item->setParentItem($parentItem);
}
/**
* We specify qty after we know about parent (for stock)
*/
$item->setQty($item->getQty() + $candidate->getCartQty());
// collect errors instead of throwing first one
if ($item->getHasError()) {
$message = $item->getMessage();
if (!in_array($message, $errors)) { // filter duplicate messages
$errors[] = $message;
}
}
}
if (!empty($errors)) {
Mage::throwException(implode("\n", $errors));
}
foreach ($items as $item) {
$this->_order->addItem($item);
}
return $items;
}
function _productToOrderItem(Mage_Catalog_Model_Product $product, $qty = 1)
{
$rowTotal = $product->getFinalPrice() * $qty;
$options = $product->getCustomOptions();
$optionsByCode = array();
foreach ($options as $option) {
$quoteOption = Mage::getModel('sales/quote_item_option')->setData($option->getData())
->setProduct($option->getProduct());
$optionsByCode[$quoteOption->getCode()] = $quoteOption;
}
$product->setCustomOptions($optionsByCode);
$options = $product->getTypeInstance(true)->getOrderOptions($product);
$orderItem = Mage::getModel('sales/order_item')
->setStoreId($this->_storeId)
->setQuoteItemId(0)
->setQuoteParentItemId(NULL)
->setProductId($product->getId())
->setProductType($product->getTypeId())
->setQtyBackordered(NULL)
->setTotalQtyOrdered($product['rqty'])
->setQtyOrdered($product['qty'])
->setName($product->getName())
->setSku($product->getSku())
->setPrice($product->getFinalPrice())
->setBasePrice($product->getFinalPrice())
->setOriginalPrice($product->getFinalPrice())
->setRowTotal($rowTotal)
->setBaseRowTotal($rowTotal)
->setWeeeTaxApplied(serialize(array()))
->setBaseWeeeTaxDisposition(0)
->setWeeeTaxDisposition(0)
->setBaseWeeeTaxRowDisposition(0)
->setWeeeTaxRowDisposition(0)
->setBaseWeeeTaxAppliedAmount(0)
->setBaseWeeeTaxAppliedRowAmount(0)
->setWeeeTaxAppliedAmount(0)
->setWeeeTaxAppliedRowAmount(0)
->setProductOptions($options);
$this->_subTotal += $rowTotal;
return $orderItem;
}
}
Then you can call it from controller:
$orderGenerator = Mage::getModel('app/ordercreate');
$orderGenerator->createOrder(array(
array(
'product' => 41, //product id
'qty' => 1
)
));
thats it. you can make product => 41 dynamic instead of static. its your choice.
I noticed laravel re-preform the insertion action when the timeout occurs
How can I shop it from retiring to insert the data again when timeout error fires ?
loop
foreach ($comments_data as $comment_data)
{
if ( ! empty($comment_data['date']))
{
$total_rating[] = $this->check_rating_value($comment_data['rating']);
$comment_id = ( new Comment() )->saveComments($shop, $comment_data, $product_id, $urls, $shop_options);
( new Comments_images() )->save_images($comment_id, $shop, $comment_data['images']);
}
}
inserting code
public function saveComments($shop, $comments_data, $product_id, $url, $shop_options)
{
$date = Carbon::parse($comments_data['date']);
if ($shop_options->filter_status == 1)
{
$comments = str_replace(explode(',', $shop_options->filter_find_words), explode(',', $shop_options->filter_alter_words), $comments_data['comment']);
} else
{
$comments = $comments_data['comment'];
}
$faker = Factory::create();
$this->shop_name = $shop;
$this->comment = $comments;
$this->rating = $this->check_rating_value($comments_data['rating']);
$this->product_id = $product_id;
$this->user_name = $faker->userName;
$this->product_url = $url;
$this->created_at = $date->toDateTimeString();
$this->country = $comments_data['country'] == 'IL' ? 'PS' : $comments_data['country'];
$this->view = 1;
$this->save();
return $this->id;
}