PHP and JSON. How to get a specific element? //Multidimensional Array - php

My JSON file
{
"shopId": 29,
"last": 46977914,
"freshfood": [
{
"freshfood_id": 2629,
"food": [
{
"food_id": 1740851,
"type": "fruit",
"status": 1
},
{
"food_id": 1730905,
"type": "vegetable",
"status": 1
},
]
}
]
}
I need to get second food_id (1730905)
I try this, but it does not work.
$string = file_get_contents("food.json");
$json_a=json_decode($string,true);
echo $GetFreshFoodId = $json_a['freshfood'][1]['freshfood_id'];

$json_a['freshfood']['food'][1]['food_id'];

It´s a syntrax error in your json file.
Your last entry in "food": [ ... ] has a comma.
That´s the reason why you get NULL when you´re run json_decode
{
"shopId": 29,
"last": 46977914,
"freshfood": [
{
"freshfood_id": 2629,
"food": [
{
"food_id": 1740851,
"type": "fruit",
"status": 1
},
{
"food_id": 1730905,
"type": "vegetable",
"status": 1
},
]
}
]
}

Related

How to take a JSON content and return it in a wordpress function (php)?

I have a wordpress endpoint and I have some json data.
Unfortunately I dont know how to return this json data in the function. I tried json_decode but it doesn't return anything. Then endpoint works. If I use json_encode it returns data, but also include linebreaks and stuff. The problem seems to be with the syntax as it is already a complete json what I have. How can I return something that is already in json syntax?
add_action('wp_ajax_nopriv_inboundCall', 'testFunction');
add_action('wp_ajax_inboundCall', 'testFunction');
function testFunction() {
echo json_decode('{
"testData": [
{
"_id": "1",
"name": "testName1"
},
{
"_id": "2",
"name": "testName2"
},
],
"testState": {
"1": [
1,
0
"2": [
1,
0
]
}
}');
die();
}
function testFunction() {
return json_decode('{
"testData": [
{
"_id": "1",
"name": "testName1"
},
{
"_id": "2",
"name": "testName2"
},
],
"testState": {
"1": [
1,
0
"2": [
1,
0
]
}
}'); }
I saved the output of json_decode to a variable and then run json_encode on that variable. Now it seems to work.
function inboundCall() {
$json = json_decode('{
"topics": [
{
"_id": "1",
"name": "davisio",
"crdate": "2022-01-17T12:40:03.430Z",
"modified": "2022-01-17T12:40:03.430Z"
},
{
"_id": "2",
"name": "LoRaWAN",
"crdate": "2022-01-17T12:40:33.848Z",
"modified": "2022-01-17T12:40:33.848Z"
},
{
"_id": "3",
"name": "Kommunale Beziehungen",
"crdate": "2022-01-19T15:17:10.094Z",
"modified": "2022-01-19T15:17:10.094Z"
},
{
"_id": "4",
"name": "Test",
"crdate": "2022-03-31T13:29:41.799Z",
"modified": "2022-03-31T13:29:41.799Z"
}
],
"serviceState": {
"1": [
1,
0,
0,
1,
0,
0,
0,
1
],
"2": [
1,
0,
0,
0,
0,
0,
0,
1
],
"4": [
1,
0,
0,
0,
0,
0,
0,
1
]
}
}');
echo json_encode($json);
die();
}

php echo from a start point to a end point

I have built a php site that takes code from a page using GET, and then echos it to the current page, but it exports text like this,
{ "selection13": [ { "name": "L" }, { "name": "100%\nA" } ], "selection7": [ { "name": "S" }, { "name": "100%\nA" } ], "selection8": [ { "name": "SS" }, { "name": "100%\nA" } ], "selection9": [ { "name": "SP" }, { "name": "100%\nA" } ], "selection10": [ { "name": "P" }, { "name": "100%\nA" } ], "selection11": [ { "name": "A" }, { "name": "100.00%\nA+" } ], "selection12": [ { "name": "H", "selection5": [ { "name": "T }, { "name": "100.00%\nA+" } ] }, { "name": "100.00%\nA+", "selection5": [ { "name": "T" }, { "name": "100.00%\nA+" } ] } ] }
I need to organizes it in to categorizes like, {L},{100%), here is the code I am currently using,
<?php
$params = http_build_query(array(
"api_key" => "()",
"format" => "json"
));
$result = file_get_contents(
'(url)'.$params,
false,
stream_context_create(array(
'http' => array(
'method' => 'GET'
)
))
);
echo gzdecode($result);
?>
Your script is outputting JSON but there appears to be a few issues with the data itself that need to be addressed first.
The next to the last "name": "T is missing a closing quote.
Section 12 has an inconsistent organization compared to the other sections. Can a section be a child of another section or is this an error?
"selection11": [
{
"name": "A"
},
{
"name": "100.00%\nA+"
}
],
"selection12": [
{
"name": "H",
"selection5": [
{
"name": "T"
},
{
"name": "100.00%\nA+"
}
]
},
{
"name": "100.00%\nA+",
"selection5": [
{
"name": "T"
},
{
"name": "100.00%\nA+"
}
]
}
]
These 2 issues need to be fixed in the JSON data you are retrieving first.
From there, the best way to reorganize this is to convert it to an array using json_decode.
$json = gzdecode($result);
$resultArray = json_decode($json);
I can't tell from your question exactly how you want to reorganize the data but use one or more of the builtin array functions to get the data in the structure you want. If you need to output it in JSON, use json_encode on the manipulated array to get the final data format. More specific help can be provided if you can be more clear on want output structure you are looking for and the format (does it need to be JSON or something else).

Elasticseach or query for comma separated values

I am saving id's in the database as comma separated and indexing the same to ElasticSearch. Now I need to retrieve if the user_id matches with the value.
For example it it saving like this in the indexing for the column user_ids (database type is varchar(500) in elasticsearch it is text)
8938,8936,8937
$userId = 8936; // For example expecting to return that row
$whereCondition = [];
$whereCondition[] = [
"query_string" => [
"query"=> $userId,
"default_field" => "user_ids",
"default_operator" => "OR"
]
];
$searchParams = [
'query' => [
'bool' => [
'must' => [
$whereCondition
],
'must_not' => [
['exists' => ['field' => 'deleted_at']]
]
]
],
"size" => 10000
];
User::search($searchParams);
Json Query
{
"query": {
"bool": {
"must": [
[{
"query_string": {
"query": 8936,
"default_field": "user_ids",
"default_operator": "OR"
}
}]
],
"must_not": [
[{
"exists": {
"field": "deleted_at"
}
}]
]
}
},
"size": 10000
}
Mapping details
{
"user_details_index": {
"aliases": {},
"mappings": {
"test_type": {
"properties": {
"created_at": {
"type": "date",
"format": "yyyy-MM-dd HH:mm:ss"
},
"deleted_at": {
"type": "date",
"format": "yyyy-MM-dd HH:mm:ss"
},
"updated_at": {
"type": "date",
"format": "yyyy-MM-dd HH:mm:ss"
},
"user_ids": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
}
},
"settings": {
"index": {
"creation_date": "1546404165500",
"number_of_shards": "5",
"number_of_replicas": "1",
"uuid": "krpph26NTv2ykt6xE05klQ",
"version": {
"created": "6020299"
},
"provided_name": "user_details_index"
}
}
}
}
I am trying with above logic, but not unable to retrieve. Can someone help on this.
Since the field user_ids is of type text any no analyzer is specified for it by default it will use standard analyzer which won't break 8938,8936,8937 into terms 8938, 8936 and 8937 and hence the id can't match.
To solve this I would suggest you to store array of ids to user_ids field instead of csv. So while indexing you json input should look as below:
{
...
"user_ids": [
8938,
8936,
8937
]
...
}
Since user ids are integer values following changes should be done in mapping:
{
"user_ids": {
"type": "integer"
}
}
The query will be now as follow:
{
"query": {
"bool": {
"filter": [
[
{
"terms": {
"userIds": [
8936
]
}
}
]
],
"must_not": [
[
{
"exists": {
"field": "deleted_at"
}
}
]
]
}
},
"size": 10000
}

Remove outer Array and change display array

If you have an array within an array, how can you remove the outer array in this laravel code. Current return array.
return view($this->_viewDefaultFile)
->with('id', $this->_formId)
->with('class', $this->_formClass)
->with('elements', $this->_formElements)
->with('ManageJs', $this->_formManageJs);
Current Results
[
0 {
"id": "id",
"group": 0,
"type": "hidden",
"label": "",
"options": [
],
"value": "1"
},
1 {
"id": "taskstream",
"group": 0,
"type": "text",
"label": "Task Stream",
"options": {
"class": "",
"validation": "required"
},
"value": "System down for maintenance"
}
]
But preferred output
[
id {
"id": "id",
"group": 0,
"type": "hidden",
"label": "",
"options": [
],
"value": "1"
},
taskstream {
"id": "taskstream",
"group": 0,
"type": "text",
"label": "Task Stream",
"options": {
"class": "",
"validation": "required"
},
"value": "System down for maintenance"
}
]
So i want to return the Array with (ID) has the key. Any help please.
Here it is:
$array = []; // your array
$new_array = [];
foreach ($array as $item) {
$new_array[$item->id] = $item;
}

parse extended json output file from cucumber with php

i am tring to parse a special json content. I got this as an output file from a cucumber execution. The goal is it to decode some values like the name the status and some other content. How can i encode that.
Another concern would be a transformation of json into a CSV.
It is not important for me to use php. Java or Perl would be an alternative.
This file I am gonna call in php with:
$jsonconntent = file_get_contents("/home/xxx/test1.json");
The json conten looks like this (I posted only the beginning):
[
{
"uri": "features/complete_ski.feature",
"id": "complete_ski_with_time",
"keyword": "Feature",
"name": "Complete_Ski_with_time",
"description": "",
"line": 1,
"elements": [
{
"id": "complete_ski_with_time;time_part_preamble",
"keyword": "Scenario",
"name": "time_part_preamble",
"description": "",
"line": 3,
"type": "scenario",
"before": [
{
"output": [
"Default Timestamp start: 1516024716000"
],
"match": {
"location": "features/support/env.rb:32"
},
"result": {
"status": "passed",
"duration": 191690
}
},
{
"match": {
"location": "capybara-2.17.0/lib/capybara/cucumber.rb:13"
},
"result": {
"status": "passed",
"duration": 52117
}
},
{
"match": {
"location": "capybara-2.17.0/lib/capybara/cucumber.rb:21"
},
"result": {
"status": "passed",
"duration": 25885
}
}
],
"steps": [
{
"keyword": "Given ",
"name": "a Android A-Party",
"line": 4,
"output": [
"Got handset with number unvisable, IMSI: notfor, android-Id: yourfone, VNC: 11111, port: 9981"
],
"match": {
"location": "features/step_definitions/idrp_steps.rb:11"
},
"result": {
"status": "passed",
"duration": 1415024760
},
"after": [
{
"match": {
"location": "features/support/env.rb:24"
},
"result": {
"status": "passed",
"duration": 264339
}
}
]
}
Use:
$data = json_decode($jsonconntent, true);
You will have the data with javascript objects as arrays, not PHP objects.
To save it as CSV, it depends on the structure of the data. In this case, it is complicated:
{
"uri": "features/complete_ski.feature",
"id": "complete_ski_with_time",
"keyword": "Feature",
"name": "Complete_Ski_with_time",
"description": "",
"line": 1,
"elements": [
{
"id": "complete_ski_with_time;time_part_preamble",
"keyword": "Scenario",
"name": "time_part_preamble",
"description": "",
"line": 3,
...
How do you put the data in the column elements? Data is so nested that it cannot be transformed into a tabular format with column headers and one value per column in each row.
As to how to access the data, you can do this:
$first_element_id = $data[0]['elements'][0]['id'];
foreach ( $data as $item ) {
$uri = $item['uri'];
foreach ( $item['elements'] as $element ) {
$name = $element['name'];
}
}
As asked in one of the comments, this is how to access the 'Default Timestamp start':
foreach ($data as $item) {
foreach ($item['elements'] as $element) {
foreach ($element['before'] as $before) {
if (isset($before['output'])) {
foreach ($before['output'] as $output) {
echo sprintf("%s\n", $output);
}
}
}
}
}

Categories