Retrieve data from the name of a directory in my database - php

I use php and laravel. I have a column named MsgBody. In this column, there is an array as follows.
"MsgBody": [
{
"MsgType": "TIMCustomElem",
"MsgContent": {
"Desc": "",
"Ext": "",
"Sound": ""
}
}
]

It seems that your data are JSON. You can decode this using json_decode.
You should be able to access what you want with something like:
$column = [
"MsgBody" => [
[
"MsgType" => "TIMCustomElem",
"MsgContent" => [
"Desc" => "",
"Data" => "{\"conversationDesc\":\"abc\"}",
"Ext" => "",
"Sound" => ""
]
]
]
];
$firstMessageContent = $column["MsgBody"][0]["MsgContent"];
$decodedData = json_decode($firstMessageContent["Data"], true);
$conversationDesc = $decodedData["conversationDesc"];
assert($conversationDesc === "abc");

Related

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

Convert array to JSON

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"
}
}
]
}

Create nested JSON with dynamic keys with PHP

I get some data from an API call and I try to construct a JSON to send it back to another API.
The final JSON must look like this:
{
"jobs": {
"MP_OFFER_ID_1": {
"job_id": "jobboard_reference_1",
"url": "url_1",
"status": 0
},
"MP_OFFER_ID_2": {
"job_id": "job_id_2",
"url": "url_2",
"status": 1
},
}
}
So under the jobs key, it's not an array of elements but a list of elements with unique keys.
And that's what I'm having trouble to get.
The data I want to parse is in an array structured like this:
Array(
[0] => Array(
[link] => some-url
[id] => 18790674
[ref] => 0015909-18790674
)
// ...
);
link has to be placed in the url key of the JSON.
id is the JSON key, in the examples it's MP_OFFER_ID_1 etc
ref has to be placed in job_id
I actually have this JSON at the end:
{
"jobs": [
[
{
"18790674": {
"job_id": "0015909-18790674",
"url": "test",
"status": 1
}
},
{
"18790678": {
"job_id": "0015892-18790678",
"url": "test",
"status": 1
}
}
]
]
}
As you can see, jobs is an array (actually it's an array of array ^^) and that's not what I want here...
I came up with this, but it was very difficult to understand what exactly you want from the very limited info in question:
<?php
$input = [
[
'id' => 18790674,
'link' => 'some-url',
'ref' => '0015909-18790674',
],
[
'id' => 18790678,
'link' => 'another-url',
'ref' => '0015909-18790678',
],
];
$output = new stdClass();
foreach ($input as $arr) {
$obj = new stdClass();
$key = $arr['id'];
$obj->job_id = $arr['id'];
$obj->url = $arr['link'];
$obj->status = '1'; // ?
$output->{$key} = $obj;
}
echo json_encode($output, JSON_PRETTY_PRINT);
Output:
{
"18790674": {
"job_id": 18790674,
"url": "some-url",
"status": "1"
},
"18790678": {
"job_id": 18790678,
"url": "another-url",
"status": "1"
}
}

Nested json string with variables in php

I will not lie to you guys: i hate nested Arrays.
So instead of my [working] code below
$query_array = Array(
"fields" => Array ("timestamp", "user.raw", "mailbox", "verb", "backend"),
"size" => 1,
"sort" => Array (Array ("#timestamp" => Array ("order" => $varOrder))),
"query" => Array (
"bool" => Array (
"must" => Array (
Array ("match" => Array ("verb" => "open")),
Array ("term" => Array ($varField => $varValue))
)
)
)
);
I want to use the [non working] code below
$query_json_string = '{
"fields" : [ "timestamp", "user.raw", "mailbox", "verb", "backend" ],
"size" : 1,
"sort" : [ { "#timestamp" : { "order" : $varOrder } } ],
"query" : {
"bool": {
"must": [
{ "match" : { "verb" : "open" } },
{ "term" : { $varField : $varValue } }
]
}
}
}';
So much easier to maintain...
But inside the single quotes the variables varOrder, varField and varValue are never expanded (i believe).
How can i use variables inside this nice and clean json string?
As I understand your question, you're simply not happy with php's array syntax. If that's the case, then don't use the old syntax. Instead use simple square brackets, which are available since version 5.4.
Doing so, your final code could be:
$query = [
"fields" => ["timestamp", "user.raw", "mailbox", "verb", "backend"],
"size" => 1,
"sort" => [["#timestamp" => ["order" => $varOrder]]],
"query" => [
"bool" => [
"must" => [
["match" => ["verb" => "open"]],
["term" => [$varField => $varValue]]
]
]
]
];
Which issn't far off your desired syntax. The only difference being => instead of :. But with the added benefit of not needing to declare objects with {}.
JSON is basically Javascript's version of a associative array.
$query_array = Array(
"fields" => Array ("timestamp", "user.raw", "mailbox", "verb", "backend"),
"size" => 1,
"sort" => Array (Array ("#timestamp" => Array ("order" => $varOrder))),
"query" => Array (
"bool" => Array (
"must" => Array (
Array ("match" => Array ("verb" => "open")),
Array ("term" => Array ($varField => $varValue))
)
)
)
);
$query_json_string = json_encode($query_array);
But if you have a problem with that, heredoc syntax should work for you..
$query_json_string = <<<JSON
{
"fields" : [ "timestamp", "user.raw", "mailbox", "verb", "backend" ],
"size" : 1,
"sort" : [ { "#timestamp" : { "order" : $varOrder } } ],
"query" : {
"bool": {
"must": [
{ "match" : { "verb" : "open" } },
{ "term" : { $varField : $varValue } }
]
}
}
}
JSON;
// if you wanted PHP array,
$query_array = json_decode($query_json_string, true);
You can switch the from single to double quotes and escape your double qoutes
$query_json_string = "{
\"fields\" : [ \"timestamp\", \"user.raw\", \"mailbox\", \"verb\", \"backend\" ],
\"size\" : 1,
\"sort\" : [ { \"#timestamp\" : { \"order\" : $varOrder } } ],
\"query\" : {
\"bool\": {
\"must\": [
{ \"match\" : { \"verb\" : \"open\" } },
{ \"term\" : { $varField : $varValue } }
]
}
}
}";

how to pass value of varibles in json

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);

Categories