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);
Related
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
I have an array:
["dyGYrcK", "tRCCMsK" ,"CM1HGi3"]
I want to convert it to json like this:
{
data: [
{
"expiry" : 0,
"tokens" : {
"0" : "dyGYrcK",
"1" : "tRCCMsK",
"2" : "CM1HGi3"
}
}
]
}
I am finding this to be very difficult. I have tried alot and I am getting this output currently:
{
"data": [
"dyGYrcK",
"tRCCMsK",
"CM1HGi3"
]
}
I am currently doing this:
return response()->json(['data' => $data], 201); //$data is array
The data array needs the keys expiry and tokens.
If you want JSON encode to set the key's you have to set them also.
So I think your array must look like:
$data = [
"expiry" => 0,
"tokens" => [
"0" => "dyGYrcK",
"1" => "tRCCMsK",
"2" => "CM1HGi3"
]
]
To get the numeric index you want inside the token structure, you need to convert your array to an object first. Then you simply add the properties to a new, "blank" object ... and finally you encode that object as JSON.
$array = ["dyGYrcK", "tRCCMsK" ,"CM1HGi3"];
$obj = new StdClass;
$obj->data[] = ['expiry' => 0, 'tokens' => (object) $array];
echo json_encode($obj);
// output:
// {"data":[{"expiry":0,"tokens":{"0":"dyGYrcK","1":"tRCCMsK","2":"CM1HGi3"}}]}
$tokens = ["dyGYrcK", "tRCCMsK" ,"CM1HGi3"] ;
$data = [
'expiry' => 0,
'tokens' => (object)$tokens
];
return response()->json(['data' => [$data]], 201);
Results in
{
"data": [
{
"expiry": 0,
"tokens": {
"0": "dyGYrcK",
"1": "tRCCMsK",
"2": "CM1HGi3"
}
}
]
}
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=YOURAPI";
$json = file_get_contents($url);
$data = json_decode($json, true);
$data['city']['name'];
foreach ($data['list'] as $day => $value) {
echo $todaystemperature = $value[temp][max];
}
?>
This has been working suddenly stopped working some reason. I keep getting on file_get_contents. Not sure what make this code mess
The JSON Data needs to be parsed based on the JSON response that you are getting.
Steps for Getting the Json Data using PHP
First you have to get the data has the json_response.
Then you have to make the json response to decode through the json code using json_decode($json,TRUE)
After that you can use foreach() for splitting up of the array that you get based on the decoded value.
While running the above URL that you have given in the code i am getting the output as follows.
Obtained JSON:
{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}],"base":"stations","main":{"temp":284.66,"pressure":1016.88,"humidity":68,"temp_min":284.66,"temp_max":284.66,"sea_level":1024.55,"grnd_level":1016.88},"wind":{"speed":4.91,"deg":97.501},"clouds":{"all":92},"dt":1476377768,"sys":{"message":0.1769,"country":"GB","sunrise":1476339772,"sunset":1476378552},"id":2643743,"name":"London","cod":200}
Hence after following up the process you can get the values like this.
PHP Code:
<?php
$url = "http://api.openweathermap.org/data/2.5/weather? q=London,uk&appid=a1fc2c19d548237a56e0edd7b79b3ebc";
$json = file_get_contents($url);
$data = json_decode($json, true);
echo $temp = $data['main']['temp']; // To convert the data to Celsius by hitting the API called api.openweathermap.
?>
Note: $data['main']['temp'] - Make sure that you get data over here and then you will succeed over here.
Output for the Json Parse is as follows for the above obtained JSON:
String Parse:
{
"coord":{
"lon":-0.13,"lat":51.51},"weather":[
{
"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}],"base":"stations","main":{
"temp":284.66,"pressure":1016.88,"humidity":68,"temp_min":284.66,"temp_max":284.66,"sea_level":1024.55,"grnd_level":1016.88},"wind":{
"speed":4.91,"deg":97.501},"clouds":{
"all":92},"dt":1476377768,"sys":{
"message":0.1769,"country":"GB","sunrise":1476339772,"sunset":1476378552},"id":2643743,"name":"London","cod":200
}
Js Eval:
{
"coord":{
"lon":-0.13,"lat":51.51},"weather":[
{
"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}],"base":"stations","main":{
"temp":284.66,"pressure":1016.88,"humidity":68,"temp_min":284.66,"temp_max":284.66,"sea_level":1024.55,"grnd_level":1016.88},"wind":{
"speed":4.91,"deg":97.501},"clouds":{
"all":92},"dt":1476377768,"sys":{
"message":0.1769,"country":"GB","sunrise":1476339772,"sunset":1476378552},"id":2643743,"name":"London","cod":200
}
Hence when you do the json_decode() for the above obtained JSON string you have the out put as follows.
array (
'coord' =>
array (
'lon' => -0.13000000000000000444089209850062616169452667236328125,
'lat' => 51.50999999999999801048033987171947956085205078125,
),
'weather' =>
array (
0 =>
array (
'id' => 804,
'main' => 'Clouds',
'description' => 'overcast clouds',
'icon' => '04d',
),
),
'base' => 'stations',
'main' =>
array (
'temp' => 284.66000000000002501110429875552654266357421875,
'pressure' => 1016.8799999999999954525264911353588104248046875,
'humidity' => 68,
'temp_min' => 284.66000000000002501110429875552654266357421875,
'temp_max' => 284.66000000000002501110429875552654266357421875,
'sea_level' => 1024.549999999999954525264911353588104248046875,
'grnd_level' => 1016.8799999999999954525264911353588104248046875,
),
'wind' =>
array (
'speed' => 4.910000000000000142108547152020037174224853515625,
'deg' => 97.501000000000004774847184307873249053955078125,
),
'clouds' =>
array (
'all' => 92,
),
'dt' => 1476377768,
'sys' =>
array (
'message' => 0.176900000000000001687538997430237941443920135498046875,
'country' => 'GB',
'sunrise' => 1476339772,
'sunset' => 1476378552,
),
'id' => 2643743,
'name' => 'London',
'cod' => 200,
)
Hence after getting the array it seems to be of Single Object with array for some of the keys that has been obtained.
Hence you can fetch the data only from this output obtained using the loop operators called foreach(). Hence by using the foreach() the array data will be coming in the loop as single manner and then it will manipulate the result.
your code seems not right, the url you are using is giving following response
{
"coord": {
"lon": -0.13,
"lat": 51.51
},
"weather": [
{
"id": 804,
"main": "Clouds",
"description": "overcast clouds",
"icon": "04d"
}
],
"base": "stations",
"main": {
"temp": 284.66,
"pressure": 1016.88,
"humidity": 68,
"temp_min": 284.66,
"temp_max": 284.66,
"sea_level": 1024.55,
"grnd_level": 1016.88
},
"wind": {
"speed": 4.91,
"deg": 97.501
},
"clouds": {
"all": 92
},
"dt": 1476377646,
"sys": {
"message": 0.0048,
"country": "GB",
"sunrise": 1476339772,
"sunset": 1476378553
},
"id": 2643743,
"name": "London",
"cod": 200
}
In the above json response i can not find any key with 'list' that is why your code breaks. This code should be fine to get the temp of the city
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=a1fc2c19d548237a56e0edd7b79b3ebc";
$json = file_get_contents($url);
$data = json_decode($json, true);
echo $temp = $data['main']['temp'];
?>
$json = file_get_contents('http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=a1fc2c19d548237a56e0edd7b79b3ebc');
$data = json_decode($json,true);
OR
$data = json_decode($json);
echo "<pre>";
print_r($data);
exit;
Here is the result
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?q=London,uk&units=imperial&cnt=1&lang=en&appid=YOURAPI";
$json = file_get_contents($url);
$data = json_decode($json, true);
echo $temp = $data['main']['temp'];
?>
I have a JSON structure like this which I want to validate.
{
"result":[{
"product_id": 1,
"client": 49,
"ticket": 2,
"sold_from_date": 1431588871,
"sold_to_date": 1433122200,
"discount_given":18,
"cheques":[{
"cheque_number" : 123456,
"amount": 6000,
"cheque_date": 1433122200,
"bank": "UCD"
},
{"cheque_number" : 456234,
"amount": 6000,
"cheque_date": 1433122200,
"bank": "AMB"
}
]
},
{
"product_id": 1,
"client": 49,
"ticket": 2,
"sold_from_date": 1433122200,
"sold_to_date": 1434688959
}]
}
I want to validate this JSON in Laravel.
I tried doing this:
$validator = \Validator::make($data, []);
$validator->each('result.product_id' , ['required|numeric']);
$validator->each('result.sold_from_date' , ['required|numeric']);
$validator->each('result.sold_to_date' , ['required|numeric']);
$validator->each('result.cheques.cheque_number' , ['sometimes|required|numeric']);
$validator->each('result.cheques.amount', ['sometimes|required|numeric']);
return $validator;
I am getting this error every time:
Attribute for each() must be an array.
Also, how can I validate cheques? Because it can or cannot be in JSON.
Create an array from json with json_decode function.
Try:
$dataarray = json_decode($data);
$validator = \Validator::make($dataarray['result'][0], [
'product_id' => 'required|numeric',
'sold_from_date' => 'required|numeric'
]);
iterate the array:
$roles = array(
'product_id' => 'required|numeric',
'sold_from_date' => 'required|numeric'
);
foreach($data as $element)
{
foreach($element as $value) {
$validator = \Validator::make($value, $roles);
}
}
I want to create a array for the following json code.
{
"homeMobileCountryCode": 310,
"homeMobileNetworkCode": 260,
"radioType": "gsm",
"carrier": "T-Mobile",
"cellTowers": [
{
"cellId": 39627456,
"locationAreaCode": 40495,
"mobileCountryCode": 310,
"mobileNetworkCode": 260,
"age": 0,
"signalStrength": -95
}
],
"wifiAccessPoints": [
{
"macAddress": "01:23:45:67:89:AB",
"signalStrength": 8,
"age": 0,
"signalToNoiseRatio": -65,
"channel": 8
},
{
"macAddress": "01:23:45:67:89:AC",
"signalStrength": 4,
"age": 0
}
]
}
I have tried with the following but it is showing parsing error in google maps geomatic api
$a = array("homeMobileCountryCode" => 310,
"homeMobileNetworkCode" => 260,
"radioType" => "gsm",
"carrier" => "T-Mobile");
$jsonVal = json_encode($a);
can anyone help me?
PHP's json_encode does not wrap integers with double quotes, which is invalid json. Try this:
$a = array("homeMobileCountryCode" => "310",
"homeMobileNetworkCode" => "260",
"radioType" => "gsm",
"carrier" => "T-Mobile");
$jsonVal = json_encode($a);
From json to Array:
$array = json_decode(/* json text /*);
From Array to Json
$json = json_encode(/* array Object */);
explanations here but you can skip to clean final code further down.
$cellTower1 = array( "cellId"=> "39627456",
"locationAreaCode"=> "40495",
"mobileCountryCode"=> "310",
"mobileNetworkCode"=> "260",
"age"=> "0",
"signalStrength"=> "-95" );
$cellTower2 = array( "cellId"=> "2222222",
"locationAreaCode"=> "22222",
"mobileCountryCode"=> "222",
"mobileNetworkCode"=> "222",
"age"=> "22",
"signalStrength"=> "-22" );
Then combine all cell towers
$allCellTowers[] = $cellTower1;
$allCellTowers[] = $cellTower2;
//etc... or could be in a loop
Now for MAC addresses and wifiAccessPoints.
$macAddress1 = array (
"macAddress"=> "01:23:45:67:89:AB",
"signalStrength" => "8",
"age" => "0",
"signalToNoiseRatio" => "-65",
"channel" => "8"
);
$macAddress2 = array (
"macAddress" => "01:23:45:67:89:AC",
"signalStrength" => "4",
"age" => "0"
);
$macAddress3 = etc...
just as for cellTower1, cellTower2 the macaddresses 1 & 2 above can be populated with a loop.
Adding them to wifiAccessPoints also can be done in a loop but it done manually below just so you understand.
$wifiAccessPoints[] = $macAddress1;
$wifiAccessPoints[] = $macAddress2;
finally the other elements all go in the resulting array to encode
$myarray = array( "homeMobileCountryCode"=> "310",
"homeMobileNetworkCode"=> "260",
"radioType"=> "gsm",
"carrier"=> "T-Mobile",
"cellTowers"=>$allCellTowers,
"wifiAccessPoints" => $wifiAccessPoints
);
$json = json_encode($myarray);
IN CLEAN CODE IT IS
$cellTower1 = array( "cellId"=> "39627456",
"locationAreaCode"=> "40495",
"mobileCountryCode"=> "310",
"mobileNetworkCode"=> "260",
"age"=> "0",
"signalStrength"=> "-95" );
$allCellTowers[] = $cellTower1;
$macAddress1 = array (
"macAddress"=> "01:23:45:67:89:AB",
"signalStrength" => "8",
"age" => "0",
"signalToNoiseRatio" => "-65",
"channel" => "8"
);
$macAddress2 = array (
"macAddress" => "01:23:45:67:89:AC",
"signalStrength" => "4",
"age" => "0"
);
$wifiAccessPoints[] = $macAddress1;
$wifiAccessPoints[] = $macAddress2;
$myarray = array( "homeMobileCountryCode"=> "310",
"homeMobileNetworkCode"=> "260",
"radioType"=> "gsm",
"carrier"=> "T-Mobile",
"cellTowers"=>$allCellTowers,
"wifiAccessPoints" => $wifiAccessPoints
);
//note that you have your first key missing though in your example
$json = json_encode($myarray);