laravel: JSON Field Comparison with Array - php

laravel-5.7/mysql
In my database, I have a json format field like this:
field name: features:
[
{"id": 1, "url": null, "name": "A"},
{"id": 2, "url": null, "name": "B"}
]
Also in its model,I wrote this
protected $casts = [
'features' => 'array'
];
Now I create an array:
$features = array();
temp = array();
temp['id'] = 1;
temp['url'] = null;
temp['name'] = A;
$features[] = temp;
temp = array();
temp['id'] = 2;
temp['url'] = null;
temp['name'] = B;
$features[] = temp;
How can I compare $features array with features field in the database?
ّI checked these:
$fff = \App\Cart::whereFeatures($features)->get()->first();
or
$fff = \App\Cart::whereFeatures(json_encode($features))->get()->first();
or
$fff = \App\Cart::whereFeatures(json_encode($features,JSON_UNESCAPED_UNICODE))->get()->first();

Use a raw expression to cast the comparison value:
$fff = \App\Cart::whereRaw('features = cast(? as json)', json_encode($features))->get();

Related

How to create JSON object in php without key name?

I am trying to create JSON Object and array in php. but It creates unwanted indexes (keys).Is there any way I can create object without Key name like $temp_obj-> No Key here $all_products_array; ???? Thanks in advance
This is How am I trying...
$combo_info = new stdClass();
$combo_info-> combo_id = $combo_id;
$combo_info-> combo_name = $combo_name;
$temp_obj = new stdClass();
for($i=0; $i<=16; $i++){
$all_products_array = array();
$all_products_array = array("product_id" => $product_id,"product_name" => $product_name);
$temp_obj->all_products_array_inside[$i] = $all_products_array;
}
$myObj = new stdClass();
$myObj->combo_info = $combo_info;
$myObj->all_products_array = $temp_obj;
$myfinalobj-> myfinalobj[$i] = $myObj;
header('Content-Type: application/json');
echo '['. json_encode($myfinalobj, JSON_PRETTY_PRINT) .']';
It will produce below result where index/key named "1" and "all_products_array_inside" are unwanted. Because I have to go myfinalobl->all_products_array->all_products_array_inside[1].product_id
but i want easy like myfinalobl->all_products_array[i].product_id
Is there any way I can create object without Key name like
$temp_obj-> No Key here $all_products_array; ????
{
"myfinalobj": {
"1": {
"combo_info": {
"combo_id": "1",
"combo_name": "Supper_deal",
},
"all_products_array": {
"all_products_array_inside": {
"1": {
"product_id": "1",
"product_name": "TV"
},
"2": {
"product_id": "2",
"product_name": "Laptop"
}
}
}
}
}
}
You are creating the key yourself (from $i), so just don't do that...
$myfinalobj->myfinalobj[$i] = $myObj;
Here you have [$i] - remove it:
$myfinalobj->myfinalobj = $myObj;

fetching multiple rows and display in json

I have a PHP code like:
while ($row2 = mysqli_fetch_assoc($check2)) {
// $leadarray[] = $row2;
$service_id[$i] = $row2['service_id'];
$row1['service_id'][$i] = $service_id[$i];
$service_name[$i] = $row2['service_name'];
$row1['service_name'][$i] = $service_name[$i];
$i++;
}
$leadarray[] = $row1;
$trimmed1['leaddetails'] = str_replace('\r\n', '', $leadarray);
echo json_encode($trimmed1);
getting output like
{
"leaddetails": [
{
"service_id": [
"7",
"2"
],
"service_name": [
"Past Control Services",
"Civil Finishing"
],
}
]
}
I want output like:
"service_id": [
1: "7",
2: "2"
],
"service_name": [
1: "Past Control Services",
2: "Civil Finishing"
],
or
[
"service_id": "7",
"service_name": "Past Control Services",
"service_id": "2",
"service_name": "Civil Finishing",
]
$trimmed1 is considered an object when passing it to json_encode (associative array in PHP) because you explicitly give it a key (considered an object property in JSON):
$trimmed1 = [];
$trimmed1['leaddetails'] = 'foobar';
This will result in json_encode encoding $trimmed1 into an object:
{
"leaddetails": "foobar"
}
To get your desired result, have $trimmed1 be considered an ARRAY when passed to json_encode.
$trimmed1[] = str_replace('\r\n', '', $leadarray); // push instead of assign
second option is not posible
you can make like this
[{"service_id":"7", "service_name":"Past Control Services"}, {"service_id":"2", "service_name":"Civil Finishing"}]
[{"service_id":"7", "service_name":"Past Control Services"}, {"service_id":"2", "service_name":"Civil Finishing"}]
using class for make like that
class Data{
$service_id;
$service_name;
}
$obj = new Array();
while ($row2 = mysqli_fetch_assoc($check2)){
$data = new Data();
$data->service_id = $row2['service_id'];
$data->service_name = $row2['service_name'];
array_push($obj, $data);
}
echo json_encode($obj);
Create the 2-dimensional array first. Then push onto the nested arrays during the loop.
$result = ["service_id" => [], "service_name" = []];
while ($row2 = mysqli_fetch_assoc($check2)) {
$result["service_id"][] = $row["service_id"];
$result["service_name"][] = $row["service_name"];
}
echo json_encode($result);

Why my code insert only one to DB when i use foreach

I need to insert data to database by use foreach
But my code only insert last one, Please help me to find out why?
Post Data
{
"APIPassword": "Test",
"Method": "Transfer",
"Data": [
{
"Account": "Test01",
"Amount": 100,
"TransactionNo": "Test1",
"dbID": "Bet1"
},
{
"Account": "Test02",
"Amount": -100,
"TransactionNo": "Test2",
"dbID": "Bet2"
}
]}
My Code
$apiPassword = $data['APIPassword'];
$method = $data['Method'];
$datas = $data['Data'];
$db = new db();
foreach ($datas as $data) {
$db->userId = '1';
$db->account = $data['Account'];
$db->amount = (float) $data['Amount'];
$db->transactionNo = $data['TransactionNo'];
$db->dbID = $data['dbID'];
$db->save();
}
Result when submit
"Account": "Test02",
"Amount": -100,
"TransactionNo": "Test2",
"db": "Bet2"
You need to instantiate a new db object each time in the for loop, in your current code you are using the same object on each iteration of the loop.
Change your code to this:
$apiPassword = $data['APIPassword'];
$method = $data['Method'];
$datas = $data['Data'];
foreach ($datas as $data) {
$db = new db();
$db->userId = '1';
$db->account = $data['Account'];
$db->amount = (float) $data['Amount'];
$db->transactionNo = $data['TransactionNo'];
$db->dbID = $data['dbID'];
$db->save();
}
What is $db = new db();, does db corresponds to a model? Try like this:
foreach ($datas as $data) {
$db = new db(); // <-- Important part
$db->userId = '1';
$db->account = $data['Account'];
$db->amount = (float) $data['Amount'];
$db->transactionNo = $data['TransactionNo'];
$db->dbID = $data['dbID'];
$db->save();
}
Perhaps in a later stage of your app you may want to update records. If dbID is your unique record key, you will do something like:
foreach ($datas as $data) {
$item = db::findFirst([
'conditions' => 'dbID = :dbID:',
'bind' => [
'dbID' => $data['dbID']
]
]);
// Record does not exist in our DB - skip or even create it?
if ($item === false) {
continue;
}
// Proceed with updating data
$item->account = $data['Account'];
$item->amount = (float) $data['Amount'];
$item->transactionNo = $data['TransactionNo'];
$item->save();
}

Creating custom JSON layout in PHP [duplicate]

This question already has answers here:
Create JSON object using PHP [duplicate]
(5 answers)
Closed 5 years ago.
I'm trying to create JSON in a PHP variable that represents the following JSON structure:
{
"nodes": [
{"id": "example#email.com", "group": 1},
{"id": "Device ID 0eb6823c8e826b6ba6a4fba7459bc77c", "group": 2},
{"id": "Device ID 9057673495b451897d14f4b55836d35e", "group": 2}
],
"links": [
{"source": "example#email.com", "target": "Exact ID 0eb6823c8e826b6ba6a4fba7459bc77c", "value": 1},
{"source": "example#email.com", "target": "Exact ID 9057673495b451897d14f4b55836d35e", "value": 1}
]
}
I'm currently not certain if the best way to do this would be to manually format the JSON layout myself, or if the above structure can be achieved using arrays and json_encode(). It would be good it someone could first confirm the best approach here.
The code I currently have is:
$entityarray['nodes'] = array();
$entityarray['links'] = array();
$entityarray['nodes'][] = '"id": "example#email.com", "group": 1';
$entityarray['nodes'][] = '"id": "Device ID 0eb6823c8e826b6ba6a4fba7459bc77c", "group": 2';
$entityarray['links'][] = '"source": "example#email.com", "target": "Exact ID 0eb6823c8e826b6ba6a4fba7459bc77c", "value": 1';
However when I view the output in JSON format there are some issues:
{
"nodes": ["\"id\": \"example#email.com\", \"group\": 1", "\"id\": \"Device ID 0eb6823c8e826b6ba6a4fba7459bc77c\", \"group\": 2"],
"links": ["\"source\": \"example#email.com\", \"target\": \"Exact ID 0eb6823c8e826b6ba6a4fba7459bc77c\", \"value\": 1"]
}
As you can see the json_encode is causing additional quotation marks with escape \ characters to be added, and each entry isn't stored as an object. Any guidance you can provide would be sincerely appreciated.
It is better using json_encode, note that you should use arrays all the way:
$entityarray['nodes'][] = array( 'id' => 'example#email.com'
, 'group' => 1
);
Try this
$result = array();
$nodes_array = array();
$temp = array();
$temp["id"] = "example#gmamil.com";
$temp["group"] = 1;
$nodes_array[] = $temp;
$temp = array();
$temp["id"] = "Device ID 0eb6823c8e826b6ba6a4fba7459bc77c";
$temp["group"] = 2;
$nodes_array[] = $temp;
$temp = array();
$temp["id"] = "Device ID 9057673495b451897d14f4b55836d35e";
$temp["group"] = 2;
$nodes_array[] = $temp;
$links_array = array();
$temp = array();
$temp["source"] = "example#email.com";
$temp["target"] = "Exact ID 0eb6823c8e826b6ba6a4fba7459bc77c";
$temp["value"] =1;
$links_array[] = $temp;
$temp = array();
$temp["source"] = "example#email.com";
$temp["target"] = "Exact ID 9057673495b451897d14f4b55836d35e";
$temp["value"] =1;
$links_array[] = $temp;
$result["nodes"] = $nodes_array;
$result["links"] = $links_array;
echo json_encode($result);

PHP JSON array from query

I'm not a php developer, but trying to get an array within an array from this query:
SELECT distinct d.DiscussionId as DiscussionId, d.AvatarId as AvatarId, d.Heading as Heading, d.body as Body, c.commentid as CommentId, c.userid as UserId, c.comment as Comment
FROM Discussion AS d
INNER JOIN Comments AS c ON d.discussionid = c.discussionid
WHERE d.DiscussionId = c.DiscussionId
The JSON output is:
[
{
"DiscussionId": "1",
"AvatarId": null,
"Heading": "New discussion heading",
"Body": "This is the discussion body",
"Comments": [
{
"DiscussionId": "1",
"CommentId": "1",
"UserId": "2",
"Comment": "This is a comment i made"
}
]
},
{
"DiscussionId": "1",
"AvatarId": null,
"Heading": "New discussion heading",
"Body": "This is the discussion body",
"Comments": [
{
"DiscussionId": "1",
"CommentId": "2",
"UserId": "2",
"Comment": "This is a second comment"
}
]
}
]
What I need is to nest all Comments in one Discussion.
the php code is below, no error but not giving the output i want, for each discussion there maybe several comments so i need DiscussionId:1 displayed only once with multilple comments array
$result = mysql_query($query,$link) or die('Errant query: '.$query);
$model = array();
$record = -1;
$currentWeID = -1;
while($e = mysql_fetch_assoc($result)){
$record++;
$model[] = array();
$model[$record]['DiscussionId'] = $e['DiscussionId'];
$model[$record]['AvatarId'] = $e['AvatarId'];
$model[$record]['Heading'] = $e['Heading'];
$model[$record]['Body'] = $e['Body'];
$model[$record]['Comments'][] = array(
'DiscussionId'=> $e['DiscussionId'],
'CommentId' => $e['CommentId'],
'UserId' => $e['UserId'],
'Comment' => $e['Comment']
);
}
print json_encode ($model);
You are selecting many comments from a single dicussion.
You should overwrite that variable instead of creating a new element at each iteration:
$model = array();
while($e = mysql_fetch_assoc($result)){
//We overwrite the same variable, that's ok
$model['DiscussionId'] = $e['DiscussionId'];
$model['AvatarId'] = $e['AvatarId'];
$model['Heading'] = $e['Heading'];
$model['Body'] = $e['Body'];
//Only comments would be an array
$model['Comments'][] = array(
'DiscussionId'=> $e['DiscussionId'],
'CommentId' => $e['CommentId'],
'UserId' => $e['UserId'],
'Comment' => $e['Comment']
);
}
try it like this:
Added Disscussion Id as an index for the array, should work for you. Just off the top of my head, not tested.
$result = mysql_query($query,$link) or die('Errant query: '.$query);
$model = array();
$record = -1;
$currentWeID = -1;
$model = array();
while($e = mysql_fetch_assoc($result)){
$record++;
$model[$e['DiscussionId']][$record]['AvatarId'] = $e['AvatarId'];
$model[$e['DiscussionId']][$record]['Heading'] = $e['Heading'];
$model[$e['DiscussionId']][$record]['Body'] = $e['Body'];
$model[$e['DiscussionId']][$record]['Comments'][] = array(
'DiscussionId'=> $e['DiscussionId'],
'CommentId' => $e['CommentId'],
'UserId' => $e['UserId'],
'Comment' => $e['Comment']
);
}
print json_encode ($model);
Try this:
$result = mysql_query($query,$link) or die('Errant query: '.$query);
$model = array();
$record = 0;
$currentWeID = -1;
while($e = mysql_fetch_assoc($result)){
$model[] = array();
$model[$record][$e['DiscussionId']]['AvatarId'] = $e['AvatarId'];
$model[$record][$e['DiscussionId']]['Heading'] = $e['Heading'];
$model[$record][$e['DiscussionId']]['Body'] = $e['Body'];
$model[$record][$e['DiscussionId']]['Comments'][] = array(
'DiscussionId'=> $e['DiscussionId'],
'CommentId' => $e['CommentId'],
'UserId' => $e['UserId'],
'Comment' => $e['Comment']
); ;
$record++;
}
print json_encode ($model);
This might help you. Dont forget to accept answer if it helps.
It's not possible with just changing the SQL query: you need to change the server-side code (PHP, as I understand) which transorms query results to JSON.

Categories