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
Related
I am using below php code for creating dynamic queries in mongo db like
..........
if ($this->programId != "") {
$query['classId'] = new MongoDB\BSON\ObjectID($this->programId);
}
......
$transportArrayCondition1 = ['transport_details' => ['$size' => 0]];
$transportArrayCondition2 = ['transport_details' => ['$elemMatch' => [
'$or' => [
['status' => ['$eq' => 'Requested']],
['status' => ['$eq' => 'Active']],
],
"approval_status" => "approved",
"allotable" => "yes",
]]];
$conditionToApply = '$or';
if($this->routeId != "")
{
$transportArrayCondition1 = ['transport_details' => ['$gt' => ['$size' => 0]]];
$transportArrayCondition2 = ['transport_details' => ['$elemMatch' => [
'$or' => [
['status' => ['$eq' => 'Requested']],
['status' => ['$eq' => 'Active']],
],
"approval_status" => "approved",
"allotable" => "yes",
"route_id" => new MongoDB\BSON\ObjectID($this->routeId)
]]];
$conditionToApply = '$and';
}
if ($this->stopId != "")
{
$transportArrayCondition1 = ['transport_details' => ['$gt' => ['$size' => 0]]];
$transportArrayCondition2 = ['transport_details' => ['$elemMatch' => [
'$or' => [
['status' => ['$eq' => 'Requested']],
['status' => ['$eq' => 'Active']],
],
"approval_status" => "approved",
"allotable" => "yes",
"route_id" => new MongoDB\BSON\ObjectID($this->routeId),
"stop_id" => $this->stopId
]]];
$conditionToApply = '$and';
}
$query[$conditionToApply] = [$transportArrayCondition1, $transportArrayCondition2];
if ($this->name != "") {
$nameArray = ['$or' => [
['fullName' => new MongoDB\BSON\Regex('^' . $this->name, 'i')],
['firstLastName' => new MongoDB\BSON\Regex('^' . $this->name, 'i')],
['registration_temp_perm_no' => new MongoDB\BSON\Regex('^' . $this->name, 'i')],
]];
array_push($query,$nameArray);
}
Actually, I have put conditions in $query variables for MongoDB commands. I am failing to create condition in if '$this->name != "" ' part of the query. I am getting $query formed like
{
"0": {
"$or": [
{
"fullName": {
"$regex": "^Vika",
"$options": "i"
}
},
{
"firstLastName": {
"$regex": "^Vika",
"$options": "i"
}
},
{
"registration_temp_perm_no": {
"$regex": "^Vika",
"$options": "i"
}
}
]
},
"schoolId": {
"$oid": "5f7aba204c610000670026d2"
},
"status": "Active",
"activeAcademicyearId": {
"$oid": "5f7abaa54c61000067002738"
},
"$or": [
{
"transport_details": {
"$size": 0
}
},
{
"transport_details": {
"$elemMatch": {
"$or": [
{
"status": {
"$eq": "Requested"
}
},
{
"status": {
"$eq": "Active"
}
}
],
"approval_status": "approved",
"allotable": "yes"
}
}
}
]
}
What I actually want is
{
"$or": [
{
"fullName": {
"$regex": "^Vika",
"$options": "i"
}
},
{
"firstLastName": {
"$regex": "^Vika",
"$options": "i"
}
},
{
"registration_temp_perm_no": {
"$regex": "^Vika",
"$options": "i"
}
}
]
"schoolId": {
"$oid": "5f7aba204c610000670026d2"
},
"status": "Active",
"activeAcademicyearId": {
............
I want array_push should add condition in $query like "$or": [...]. It should not add condition like "0": {"$or": [... ]}, I have tried a lot of things since morning but could not find any solution. Kindly help !!!
Since $query is associated array like structure and it already contains $or key in which you want to add the element you may need to update it as below.
Change $nameArray as below
$nameArray = [
['fullName' => new MongoDB\BSON\Regex('^' . $this->name, 'i')],
['firstLastName' => new MongoDB\BSON\Regex('^' . $this->name, 'i')],
['registration_temp_perm_no' => new MongoDB\BSON\Regex('^' . $this->name, 'i')],
];
array_push add elements add the end of the array
If you want to merge with existing $or values then we can use array_merge to merge both as array and then reassign it to existing $or key in $query
$query['$or'] = array_merge($nameArray, $query['$or']);
Or
$query['$or'] = $nameArray + $query['$or'];
If you want to replace then you can just reassign the changed $nameArray variable to $query['$or']
$query['$or'] = $nameArray;
I have two arrays.
The first one is about exchange-rate and the display in my console is like this :
{
"exchange_rate": [
{
"id": "978",
"start_dateTime": "2021-08-01 07:35:02",
"target_value": "1.00000",
"currency_value_euro": "0.84097",
"currency_value_dollar_us": "1.00000",
"id_currency": "1",
"currency": "Dollar am\u00e9ricain",
"currency_symbol": "$US"
},
{
"id": "980",
"start_dateTime": "2021-08-01 07:35:02",
"target_value": "1.00000",
"currency_value_euro": "1.17454",
"currency_value_dollar_us": "0.71600",
"id_currency": "2",
"currency": "Livre sterling",
"currency_symbol": "\u00a3"
}
]
}
These data came from the database and I can display it by choosing particular dates with jQuery.
The second array contains only id_currency which in my console is like this : Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5
On my website, I want to be able to display specific exchange rate by specific currency and dates.
And here my problem appears, I can't find the way to loop on the first array, and loop again inside, on the second array and compare both like if first array has id_currency 1 and second array has id_currency 1 then display the complete line from first array.
I've tried several things but nothing works, at last i've tried this :
foreach ($res as $row){
$idBDD = $row['id_currency'];
$symbolBDD = $row['currency_symbol'];
echo $idBDD;
echo $symbolBDD;
//var_dump($row);
/*foreach ($arr as $line){
$idCheckbox = $line;
echo $idCheckbox;
}
if ($idBDD == $idCheckbox){
echo 'fine';
}
*/
}
I'll be grateful for your help
You need to access the array with $res["exchange_rate"] and loop through it then.
<?php
$res = [
"exchange_rate" => [
[
"id" => "978",
"start_dateTime" => "2021-08-01 07:35:02",
"target_value" => "1.00000",
"currency_value_euro" => "0.84097",
"currency_value_dollar_us" => "1.00000",
"id_currency" => "1",
"currency" => "Dollar américain",
"currency_symbol" => "\$US"
],
[
"id" => "980",
"start_dateTime" => "2021-08-01 07:35:02",
"target_value" => "1.00000",
"currency_value_euro" => "1.17454",
"currency_value_dollar_us" => "0.71600",
"id_currency" => "2",
"currency" => "Livre sterling",
"currency_symbol" => "£"
]
]
];
$output = null;
foreach ($res["exchange_rate"] as $row) {
if (!isset($output)) {
$output = $row;
}
$output = array_intersect_assoc($output, $row);
}
var_dump($output);
I think you could do it like this, of course if you're inside the loop, you won't need to put indices.
read more array_diff()
https://www.php.net/manual/pt_BR/function.array-diff.php
$array = [
"exchange_rate" => [
[
"id" => "978",
"start_dateTime" => "2021-08-01 07:35:02",
"target_value"=> "1.00000",
"currency_value_euro"=> "0.84097",
"currency_value_dollar_us"=> "1.00000",
"id_currency"=> "1",
"currency"=> "Dollar am\u00e9ricain",
"currency_symbol" => "US"
],[
"id"=> "980",
"start_dateTime"=> "2021-08-01 07=> 35=> 02",
"target_value"=> "1.00000",
"currency_value_euro"=> "1.17454",
"currency_value_dollar_us"=> "0.71600",
"id_currency"=> "2",
"currency"=> "Livre sterling",
"currency_symbol"=> "\u00a3"
]
]
];
$array1 = $array['exchange_rate'][0];
$array2 = $array['exchange_rate'][1];
$result = array_diff( $array1, $array2);
var_dump($result);
I'm making an API for getting some data. My API gives object data like given, given object I wanted to format some data inside object:
{
"data": [
{
"productId": 55,
"productTitle": "Test product",
"variation": {
"Color": "Red",
"Size": "XS",
"din": "10190537",
"product_id": 55,
"name": [
"Color",
"Size"
],
"value": [
"Red",
"XS"
]
},
"din": "10190537",
"markets": [
{
"id": 11,
"name": "paytmmall",
"displayName": "PayTm Mall",
"identifierName": "Product_Id"
}
]
}
]
}
In this object I want data like given
{
"data": [
{
"productId": 55,
"productTitle": "this is test from hariom",
"variation": {
"Color": "Red",
"Size": "XS",
"din": "10190537",
"product_id": 55,
"variationTypes": [
{
"name": "Color",
"value": "Red"
},
{
"name": "Size",
"value": "XS"
}
],
},
"din": "10190537",
"markets": [
{
"id": 11,
"name": "paytmmall",
"displayName": "PayTm Mall",
"identifierName": "Product_Id"
}
]
}
]
}
Here Is my Controller Name
public function MarketMapping(Request $request)
{
$sellerId = Auth::guard('seller-api')->user();
$page = $request->has('pageNumber') ? $request->get('pageNumber') : 1;
$limit = $request->has('perPage') ? $request->get('perPage') : 10;
$variationFromInvTbl = ProductInventory::select('Color', 'Size', 'din', 'product_id')->where('seller_id', $sellerId->id)->where('status', 'active')->limit($limit)->offset(($page - 1) * $limit)->get();
$dataArray = array();
foreach($variationFromInvTbl as $key => $varitionValue)
{
$prodtsFromLivetbl = ProductsLive::select('productTitle', 'product_id')->where('product_id', $varitionValue->product_id)->get();
foreach ($prodtsFromLivetbl as $key => $value)
{
$marketChannelData = DB::table('market_channels')
->join('sellers_market_channels', 'market_channels.name', '=', 'sellers_market_channels.key')
//->join('market_product_mappings', 'market_channels.id', '=', 'market_product_mappings.market_id')
->select('market_channels.id','market_channels.name', 'market_channels.displayName','market_channels.identifierName') //'market_product_mappings.identifierValue'
->where('sellers_market_channels.seller_id', $sellerId->id)
->where('sellers_market_channels.value', 1)
->get();
$maketProductMap = MarketProductMapping::where('seller_id', $sellerId->id)->where('product_id', $varitionValue->product_id)->where('din', $varitionValue->din)->pluck('identifierValue');
if (count($maketProductMap))
{
$marketChannelData[$key]->value = $maketProductMap[0];
}
$varitionValue['name']= array_keys($varitionValue->only(['Color', 'Size']));
$varitionValue['value'] = array_values($varitionValue->only(['Color', 'Size']));
$dataObject = ((object)[
"productId" => $value->product_id,
"productTitle" => $value->productTitle,
"variation" => $varitionValue,
"din" => $varitionValue['din'],
"markets" => $marketChannelData
]);
array_push($dataArray,$dataObject);
}
}
if($variationFromInvTbl)
{
$response['success'] = true;
$response["page"] = $page;
$response["itemPerPage"] = $limit;
$response["totalRecords"] = $this->CountMarketMapping($page, $limit, $sellerId->id);
$response['data'] = $dataArray;
return response()->json($response, 200);
}else{
$response['success'] = false;
$response['data'] = $prodtsFromLivetbl;
return response()->json($response, 409);
}
}
You are using laravel's only() method which returns an associative array.
You wish to convert each key-value pair into a subarray containing two associative elements -- the original key will be the value of the name element
and the original value will be the value of the value element.
By passing the original array keys and array values into array_map(), you can iterate them both synchronously.
compact() is a perfect native function to create the desired associative subarrays from the iterated parameters.
Code: (Demo)
$variations = $varitionValue->only(['Color', 'Size']);
$dataObject = (object)[
// ... your other data
'variations' => array_map(
function($name, $value) {
return compact(['name', 'value']);
},
array_keys($variations),
$variations
),
// ...your other data
];
var_export($dataObject);
Output:
(object) array(
'variations' =>
array (
0 =>
array (
'name' => 'Color',
'value' => 'Red',
),
1 =>
array (
'name' => 'Size',
'value' => 'XS',
),
),
)
This script will help you
<?php
$data = [
"variation" => [
[
"Color" => "Red",
"Size" => "XS",
"din" => "10190537",
"product_id" => 55,
"name" => [
"0" => "Color",
"1" => "Size"
],
"value" => [
"0" => "Red",
"1" => "XS"
]
]
]
];
for ($i=0; $i < count($data["variation"]); $i++) {
$data["variation"][$i]["data"]["name"] = $data["variation"][$i]["name"];
$data["variation"][$i]["data"]["value"] = $data["variation"][$i]["value"];
unset($data["variation"][$i]["name"]);
unset($data["variation"][$i]["value"]);
}
print_r($data);
output
Array
(
[variation] => Array
(
[0] => Array
(
[Color] => Red
[Size] => XS
[din] => 10190537
[product_id] => 55
[data] => Array
(
[name] => Array
(
[0] => Color
[1] => Size
)
[value] => Array
(
[0] => Red
[1] => XS
)
)
)
)
)
I have an application that retrieves data from a mysql database and generates a json output with php to send to a plugin.
I'm generating the following json output from php:
{
"mapwidth":"1300",
"mapheight":"1000",
"categories":"[]",
"levels":{
"id":"lots",
"title":"Lots",
"map":"maps\/lot-map.svg",
"minimap":"",
"locations":[
{
"id":"lot1",
"title":"Lot 1",
"pin":"hidden",
"description":"<p>Status: <b style=\\\"color: #8eba5e;\\\">Available<\/b><br>Size:\u00a0<b>850 sqm<\/b><br>Please get in touch for an Offer.<\/p>",
"link":null,
"x":"0.4849",
"y":"0.4629",
"fill":null,
"category":"false",
"action":"tooltip"
}
]
},
"maxscale":"1.8"
}
But the format is incorrect. Should be like the following tested json file:
{
"mapwidth": "1300",
"mapheight": "1000",
"categories": [],
"levels": [
{
"id": "lots",
"title": "Lots",
"map": "maps/lot-map.svg",
"minimap": "",
"locations": [
{
"id": "lot12",
"title": "Lot 12",
"pin": "hidden",
"description": "<p>Status: <b style=\"color: #8eba5e;\">Available</b><br>Size: <b>850 sqm</b><br>Please get in touch for an Offer.</p>",
"link": "#more",
"x": "0.3726",
"y": "0.4565"
}
]
}
],
"maxscale": 1.8
}
The difference is in the "levels" key.
This is my php code:
$results = array(
'mapwidth' => '1300',
'mapheight' => '1000',
'categories' => '[]'
);
$results['levels'] = array(
'id' => 'lots',
'title' => 'Lots',
'map' => 'maps/lot-map.svg',
'minimap' => ''
);
if ($lotes)
{
// build usable array
foreach($lotes['results'] as $lote)
{
$results['levels']['locations'][] = array(
'id' => $lote['slug'],
'title' => $lote['title'],
'pin' => $lote['pin'],
'description' => $lote['description'],
'link' => $lote['link'],
'x' => $lote['position_x'],
'y' => $lote['position_y'],
'fill' => $lote['fill'],
'category' => $lote['category'],
'action' => $lote['action']
);
}
}
else
$results['error'] = lang('core error no_results');
$results['maxscale'] = '1.8';
// display results using the JSON formatter helper
display_json($results);
Any suggestions? Thanks
You need to make the levels a multidimensional array.
$results['levels'] = array();
$results['levels'][0] = array(
'id' => 'lots',
'title' => 'Lots',
'map' => 'maps/lot-map.svg',
'minimap' => ''
);
Then when you append to do, do it as follows:
$results['levels'][0]['locations'][] = array(
foreach ($ordersList as $object) {
$entityid = $object->entity_id; //how to give this $entityid with in json
$json='{
"orderNo":$entityid, //here i want to assign the value of $entityid
"customerCode": $customerid,
"dateOrdered": "08-07-2015",
"warehouseId" : ,
"orderLineList":
[
"productId": 1000002,
"qty": 6,
"price": 10
]
}';
}
$data = json_decode($json);
$data_string= json_encode($data);
Don't write JSON strings by hand.
$data = [
"orderNo" => $entityid, //here i want to assign the value of $entityid
"customerCode" => $customerid,
"dateOrdered" => "08-07-2015",
"warehouseId" => null ,
"orderLineList" => [
"productId": 1000002,
"qty": 6,
"price": 10,
],
];
$json = json_encode($data);
json_decode() would give an error for this:
{"orderLineList": [ "productId": 1000002 ]}
Try this code:
foreach ($ordersList as $object) {
//Start with a PHP array
//Don't mess with concatenation, you will get tangled with opening & closing quotes.
//If your information comes in a json format. Use json_decode() to convert it into a PHP array.
//$dateOrder,$warehouseId,$object->customer_id are fictious variables. Replace them with real values.
$orderArray[] = [
'orderNo' => $object->entity_id,
'customerCode' => $object->customer_id,
'dateOrdered' => $dateOrdered,
'warehouseId' => $warehouseId,
'orderLineList' => [
'productId': 1000002,
'qty': 6,
'price': 10
]
];
}
$data_string = json_encode($orderArray);