format rest Api group field by category - php

I am new to API I used Codeigniter to create an APi from a MySql Databse Products which have
the field : Amount , quantity, customerName, CustomerPhone, CustomerAddress
the rsult looks:
```[
{
"Id": "1",
"Amount": "21542",
"quantity": "52",
"customerName": "John",
"CustomerPhone": "254215",
"CustomerAddress": "road tvz120",
},```
but i want it to look this way:
```[
{
"Id": "1",
"Amount": "21542",
"quantity": "52",
"customerInfo":{
"customerName": "John",
"CustomerPhone": "254215",
"CustomerAddress": "rue tvz120"},
},```
I mean to group the 3 field concernign customers with the name customer info
my php code is
```public function index_get($id = 0)
{
if(!empty($id)){
$data = $this->db->get_where("Products", ['Id' => $id])->row_array();
}else{
$data = $this->db->get("Products")->result();
}
$this->response($data, REST_Controller::HTTP_OK);
}```

Your Products format is based on database, therefore if you want to change the result format, you have to construct it manually. You need to loop the result before returning the data.
if(!empty($id)){
$data = $this->db->get_where("Products", ['Id' => $id])->row_array();
}else{
$data = $this->db->get("Products")->result();
$newdata = array();
foreach($data as $row)
{
$newdata[] = array(
"Id" => $row->id,
"Amount" => $row->amount,
"quantity" => $row->quantity,
"customerInfo" => array(
"customerName" => $row->customerName,
"CustomerPhone" => $row->CustomerPhone,
"CustomerAddress" => $row->CustomerAddress,
)
);
}
$data = $newdata;
}
$this->response($data, REST_Controller::HTTP_OK);

You cannot perform this via query, you'll have to loop through the result and change it to the desired format, like so -
if(!empty($id)){
$result = $this->db->get_where("Products", ['Id' => $id])->result();
// I'll advise to use result() here instead of row_array() so that you don't face any issue when there's only one row.
}else{
$result = $this->db->get("Products")->result();
}
foreach($result as $res){
$new_result[] = array(
"Id" => $res->Id,
"Amount" => $res->Amount,
"quantity" => $res->quantity,
"customerInfo" => array(
"customerName" => $res->customerName,
"CustomerPhone" => $res->CustomerPhone,
"CustomerAddress" => $res->CustomerAddress
)
);
}
$this->response($new_result, REST_Controller::HTTP_OK); // send newly created array instead
See if this helps you.

Related

Update array with post values

im currently trying to update an array with values from another one.
Basically there is a form where you can update data for an object, the form sends a json array like so:
{
"name": "Test2",
"address": "Adresas 2",
"object_id": "44",
"job_id": [
"31",
"33"
],
"amount": [
"500",
"500"
]
}
My goal is to update another array that is being fetched from the database with values of job_idd and amount.
The array from database looks like so:
{
"jobs": [
{
"id": "31",
"amount": "500",
"have": 250
},
{
"id": "33",
"amount": "500",
"have": 0
}
]
}
I need to update the second array values "amount" with the posted values from the first array "amount", but so that the second array still has the original "have" values
I tried using nested foreach method:
$object_id = $_POST['object_id'];
$data = json_encode($_POST);
$json = json_decode($data, true);
$i = 0;
foreach($json['job_id'] as $item) {
$job_id = $item;
$query33 = "SELECT * FROM `objektai` WHERE id='$object_id'";
$result33 = mysqli_query($conn, $query33) or die(mysqli_error($conn));
while($row2 = mysqli_fetch_array($result33)){
$job_info = $row2['info'];
}
$json_22 = json_decode($job_info, true);
foreach ($json_22['jobs'] as $key2 => $entry2) {
$have = $json_22['jobs'][$key2]['have'];
}
$result["jobs"][] = array(
'id' => $job_id,
'kiekis' => $json['amount'][$i],
'turima' => $have,
);
$i++;
}
Usinng the example above the foreach prints the values 2 times and my updated json "have"
has a value of 0, the "amount" entries are updated correctly
Thanks in advance for you help!
UPDATE
adding var_export($_POST):
array ( 'name' => 'Test2',
'address' => 'Adresas 2',
'object_id' => '44',
'job_idd' => array (
0 => '31',
1 => '33',
),
'darbo_kiekis' => array (
0 => '500',
1 => '500',
),
)
When you're looping through the array from the database, you need to compare the id value with $obj_id.
I've also shown below how to use a prepared statement to prevent SQL injection.
I've removed lots of unnecessary code:
No need to convert $_POST to/from JSON.
Use $i => in the foreach loop to get the array index.
You don't need a while loop when processing the query results if it only returns one row.
You don't need $key2, you can just use $entry2.
$object_id = $_POST['object_id'];
$query33 = "SELECT * FROM `objektai` WHERE id = ?";
$stmt33 = $conn->prepare($query33);
$stmt33->bind_param('i', $job_id);
foreach($_POST['job_id'] as $i => $job_id) {
$stmt33->execute();
$result33 = $stmt33->get_result();
$row2 = $result33->fetch_assoc();
$job_info = $row2['info'];
$json_22 = json_decode($job_info, true);
foreach ($json_22['jobs'] as $entry2) {
if ($entry2['id'] == $job_id) {
$result["jobs"][] = array(
'id' => $job_id,
'kiekis' => $json['amount'][$i],
'turima' => $entry2['have']
);
}
}
}

Loop through Categories and its Products in PHP Laravel

I have to create an array with the categories array and its related products i'm fetching category with all related products using this query
$categoryData= Category::with('product')->get();
Data is beign fetched properly, using this loop to get data in the format given below:
foreach($categoryData as $row){
$categoriesData[] = [
'id' => $row->id,
'title' => $row->title,
];
foreach($row->product as $rowproduct){
$categoriesData['product_details'][] = [
'product_name' => $rowproduct->name,
'product_price' => $rowproduct->price
];
}
}
Format (It should be something like this) :
{
"categoriesData": {
"0": {
"id": 1,
"category_name" : "Name 1",
"product_details": [
{
"id": 1,
"product_name": Product Name,
},
],
"1": {
"id": 2,
""category_name" ": "Name 2",
"product_details": [
{
"id": 1,
"product_name": product name,
},
},
but through present loop all product is getting saved in one array. It is not saving inside category.
Any help is highly appreciated
You can do this with Collection methods if you wanted to, basically just map:
$array = $categoryData->map(function ($category) {
return [
'id' => $category->id,
'title' => $category->title,
'product_details' => $category->products->map(function ($product) {
return [
'product_name' => $product->name,
'product_price' => $product->price,
];
}),
];
})->all();
Though this is going in the direction of using a transformer or API resource to format this data.
Hi I think this is what you're looking for :
foreach ($categoryData as $key => $row) {
$categoriesData[$key] = [
'id' => $row->id,
'title' => $row->title,
];
foreach ($row->product as $rowproduct) {
$categoriesData[$key]['product_details'][] = [
'product_name' => $rowproduct->name,
'product_price' => $rowproduct->price
];
}
}

php - How to insert a foreach loop inside a multidimensional array

How to insert a foreach loop inside a multidimensional array ?
I have a multidimensional array that I use to connect my website to Mailchimp. I have to check with a foreach loop the number of products that the user buys, and add these insiede a array call "lines".
This is at moment my json code, that after I will send to Mailchimp:
$json_data = '{
"id": "2'. $order->id .'",
"customer": {
"id": "71",
"email_address": "'.$order->email.'",
"opt_in_status": true,
"company": "'.$order->company_name.'",
"first_name": "'.$order->pad_firstname.'",
"last_name": "'.$order->pad_lastname.'",
"orders_count": 1,
"total_spent": 86
},
"checkout_url": "https://www.mywebsite.it/en/checkout/confirmation/",
"currency_code": "EUR",
"order_total": 86,
"lines"[{
'.$line_result.'
}]
}';
The $line_result is where I try to add the array of the products.
I know is wrong.
all the array inside the "lines" need be like this:
"lines":[
{
data product 1 ...
},
{
data product 2 ...
}
]
This is my foreach:
foreach ($order->pad_products as $product) {
$line_result['line'] = array(
"id" => "$order->id",
"product_id" => "$product->pad_product_id",
"product_title" => "$product->title",
"product_variant_id" => "$product->id",
"product_variant_title" => "$product->title",
"quantity" => "$product->pad_quantity",
"price" => "$product->prezzo",
);
};
what is the correct way to insert this data and create a multidimensional array like the one I need?
Thank you.
You just need to store all $line_result in global variable, and then, bind it to your json model :
$results = [];
foreach ($order->pad_products as $product) {
$results[] = array(
"id" => $order->id,
"product_id" => $product->pad_product_id,
"product_title" => $product->title,
"product_variant_id" => $product->id,
"product_variant_title" => $product->title,
"quantity" => $product->pad_quantity,
"price" => $product->prezzo,
);
};
$data = json_decode($json_data, true);
$data['lines'] = $results;
$json = json_encode($data);
EDIT : Script array to json
$lines = [];
foreach ($order->pad_products as $product) {
$lines[] = array(
"id" => $order->id,
"product_id" => $product->pad_product_id,
"product_title" => $product->title,
"product_variant_id" => $product->id,
"product_variant_title" => $product->title,
"quantity" => $product->pad_quantity,
"price" => $product->prezzo,
);
}
$data = [
'id' => '2'.$order->id,
'customer' => [
'id' => '71',
'email_address' => $order->email,
'opt_in_status' => true,
'company' => $order->company_name,
'first_name' => $order->pad_firstname,
'last_name' => $order->pad_lastname,
'orders_count' => 1,
'total_spent' => 86
],
'checkout_url' => 'https://www.mywebsite.it/en/checkout/confirmation',
'currency_code' => 'EUR',
'order_total' => 86,
'lines' => $lines
];
$jsonData = json_encode($data, JSON_UNESCAPED_UNICODE);
I want say thank you to #adrianRosi for the help and the input he gives me.
In the end I find my solution, that it's json_encode the array before add into $data in json format.
in this way:
$product_list = [];
foreach ($order->pad_products as $product) {
$product_list[] = array(
"id" => "$id",
"..." => "...",
);
};
$data_products['lines'] = $product_list;
$json_products = json_encode($data_products);
$json_products_edit = substr($json_products, 1, -1); // to delete the {}
$prezzo_totale = $order->pad_price_total;
$json_data = '{
...
...
'.$json_products_edit.'
}';

Array to string conversion in JSON input Laravel

I'm trying to input some JSON data in a table between Laravel, but i'm receiving the Array to string Conersion.
This is my JSON:
{
"data": [
{
"client_id": "3",
"vehicle_id": "3",
"cart1_id": "3",
"cart2_id": "3",
"driver1_id": "3",
"driver2_id": "3",
"shipper_id": "3",
"transportationtype_id": "1",
"startdatetime": "2018-10-10 11:00:00",
"enddatetime": "2018-10-10 18:00:00",
"consultnumber": "3",
"consultvalidity": "2018-10-20",
"escorted": "1",
"escortcompany": "Teste",
"escortplate": "ABC-1234",
"escorttrackingtecnology": "1",
"escorttrackingserial": "123",
"contactname": "José",
"contacttel": "17-997157517",
"decoy": "0",
"decoytrackingtecnology": "1",
"decoyserial": "9999",
"decoysite": "www",
"decoylogin": "123",
"decoypassword": "bacd",
"charged": "1",
"charge": [
{
"description": "Teste Carga 1",
"nf": "1234",
"amount": "1000.00"
},
{
"description": "Teste Carga 2",
"nf": "4321",
"amount": "2000.00"
}
]
}
]
}
And this is my Controller:
public function storeapi(Request $request)
{
$array = $request->all();
$insertedIds = [];
foreach ($array['data'] as $row) {
$validator = Validator::make($array['data'], [
$row['vehicle_id'] => 'required',
$row['driver1_id'] => 'required',
]);
if($validator->fails()) {
return response()->json([
'message' => 'Validation Failed',
'errors' => $validator->errors()->all()
], 422);
}
$newSm = Sm::create([
'client_id' => $row['client_id'],
'veiculo_id' => $row['vehicle_id'],
'carreta1_id' => $row['cart1_id'],
'carreta2_id' => $row['cart2_id'],
'motorista1_id' => $row['driver1_id'],
'motorista2_id' => $row['driver2_id'],
'embarcador_id' => $row['shipper_id'],
'tipotransporte_id' => $row['transportationtype_id'],
'inicioprevisao' => $row['startdatetime'],
'fimprevisao' => $row['enddatetime'],
'nroliberacao' => $row['consultnumber'],
'datavigencia' => $row['consultvalidity'],
'escolta' => $row['escorted'],
'empresa' => $row['escortcompany'],
'placaescolta' => $row['escortplate'],
'tecnologia_id' => $row['escorttrackingtecnology'],
'serial' => $row['escorttrackingserial'],
'nomecontato' => $row['contactname'],
'telefonecontato' => $row['contacttel'],
'isca' => $row['decoy'],
'tecnologiaisca_id' => $row['decoytrackingtecnology'],
'serialisca' => $row['decoyserial'],
'siteisca' => $row['decoysite'],
'login' => $row['decoylogin'],
'senha' => $row['decoypassword'],
'status_id' => "1"
]);
$insertedIds[] = $newSm->id;
foreach ($row['charge'] as $key => $charge){
$carga = new Carga();
$carga->descricao = $charge['description'];
$carga->nf = $charge['nf'];
$carga->valor = $charge['amount'];
$carga->sm_id = $insertedIds;
$carga->save();
}
return response()->json($insertedIds, 201);
}
}
And this is the returned error:
Illuminate \ Database \ QueryException
Array to string conversion (SQL: insert into cargas (descricao, nf, valor, sm_id, updated_at, created_at) values (Teste Carga 1, 1234, 1000.00, 89, 2018-10-11 16:55:57, 2018-10-11 16:55:57))
You have $carga->sm_id = $insertedIds; which is writing an array to the database. You cannot do this. Either store a single sm_id, or serialize the array using serialize($carga->sm_id), or normalize your database if you need multiple IDs for this row, and create a second table and use a foreign key.
EDIT:
Checking your code, you probably want this instead:
$carga->sm_id = $newSm->id;
$carga->save();
...
Use this:
$insertedIds[] = $newSm->id;
foreach ($row['charge'] as $key => $charge){
$carga = new Carga();
$carga->descricao = $charge['description'];
$carga->nf = $charge['nf'];
$carga->valor = $charge['amount'];
$carga->sm_id = $newSm->id;
$carga->save();
}
as $newSm->id is initializing in array $insertedIds[] and $carga->sm_id in database table Cargas may be of type integer or string

MySQL results to JSON with PHP

I've seen lots of similar question on here, but I haven't been able to get my desired output. Could someone please help me out? How can generate the following JSON structure? My query is fine, I just can't figure out how to loop through and get this. Thanks
DESIRED OUTPUT
{
"players": [
{
"id": 271,
"fname": "Carlos",
"lname": "Beltran",
"position": "OF",
"stats": [
{
"year": "2010",
"hr": 32,
"rbi": 99,
"team": "NYM"
},
{
"year": "2011",
"hr": 35,
"rbi": 100,
"team": "STL"
},
{
............
}
]
},
{
........
}
]
}
CURRENT OUTPUT
{"0":{"cbs_id":"18817","fname":"Carlos","lname":"Beltran"},"stats":[{"year":"2007","hr":"33","rbi":"112"}]}
{"0":{"cbs_id":"174661","fname":"Willie","lname":"Bloomquist"},"stats":[{"year":"2007","hr":"2","rbi":"13"}]}
{"0":{"cbs_id":"1208693","fname":"Brennan","lname":"Boesch"},"stats":[{"year":"2010","hr":"14","rbi":"67"}]}
Which is generated with: (I know I'm way off)
if ($result = mysqli_query($link, $sql)) {
$player = array();
while ($row = $result->fetch_assoc())
{
$player[] = array (
'cbs_id' => $row['cbs_id'],
'fname' => $row['fname'],
'lname' => $row['lname']
);
$player['stats'][] = array(
'year' => $row['year'],
'hr' => $row['hr'],
'rbi' => $row['rbi']
);
}
$json = json_encode($player);
echo "<pre>$json</pre>";
mysqli_free_result($result);
}
}
NOTE: Each player can have more than one "stats" record (year, hr, rbi, etc)
This may give what you want:
$players = array();
while ($row = $result->fetch_assoc())
{
$id = (int)$row['cbs_id'];
if ( ! isset($players[$id]))
{
// New player, add to $players array.
// For the moment index players by ID so stats can be easily added
// to an existing player. Without indexing (using $players[] = ...),
// the same player would be added for each stats record related to
// him.
$players[$id] = array(
'id' => $id,
'fname' => $row['fname'],
'lname' => $row['lname'],
'stats' => array()
);
}
// Add the stats
$players[$id]['stats'][] = array(
'year' => (int)$row['year'],
'hr' => (int)$row['hr'],
'rbi' => (int)$row['rbi']
);
}
// Players are indexed by their ID in $players but need to be contained in
// a JSON array, so use array_values() to remove indices, e.g. convert
//
// array(
// 271 => array('id' => 271, ...),
// ...
// )
//
// to
//
// array(
// array('id' => 271, ...),
// ...
// )
//
$data = array('players' => array_values($players));
$json = json_encode($data);
Eventually you might leave out the integer casts and let PHP automatically convert stringified numeric data (that's the default behaviour with MySQL query results) back to PHP numbers by using the MYSQLI_OPT_INT_AND_FLOAT_NATIVE mysqli connection option as described in example #5 of this page. Note that it requires the mysqlnd library to be used by PHP (you can check that with phpinfo).
You need an associative array. Something like this should get you started:
$data = array(
'players' => array(
array(
'id' => 271,
'fname': 'Carlos',
'lname': 'Beltran',
'position': 'OF',
'stats' => array(
array(
'year' => 2010,
'hr': 32,
'rbi': 99,
'team': 'NYM'
),
...
)
),
...
)
);
To encode it into json, use json_encode:
$json = json_encode($data);

Categories