Getting REST API results in PHP - php

I'm trying to get a specific value out of a JSON file in PHP how could this be done. I'm trying to find the value of "allTests": [{"TestOnBlazemeterWasBroken": true}] in the code below and check if it is there and if it equals to true. the value can be true or false and 'TestOnBlazemeterWasBroken' can be also 'TestOnBlazemeterFailed' or 'TestOnBlazemeterWasSuccessful' it depends on the success of an API test
The json file from where i need to find the value "allTests": [{"TestOnBlazemeterWasBroken": true}]
{
"id": "311e6d5a-3f20-42d2-b276-80c5f33f1d7f",
"name": "Testing",
"timestamp": "2021-07-02T10:39:48.544Z",
"collection_id": "6cd6e3b9-cce9-4746-83ca-9349708d3b18",
"folder_id": 0,
"environment_id": "db26e19d-4373-4004-9ad2-348545c6f521",
"totalPass": 1,
"totalFail": 0,
"results": [
{
"id": "bb1b9473-2f66-4153-8996-88cf40715ba6",
"name": "retrieving ID's",
"url": "https://a.blazemeter.com/api/v4/tests?workspaceId=894576&limit=20&hasExecutions=true&filterByActivePlatform=false",
"time": 1116,
"responseCode": {
"code": 200,
"name": "OK"
},
"tests": {},
"testPassFailCounts": {},
"times": [
1116
],
"allTests": [
{}
]
},
{
"id": "c694f16e-8195-4696-a874-fdaed51bbfd7",
"name": "Session summary1",
"url": "https://a.blazemeter.com/api/v4/tests/9661550/sessions-summaries",
"time": 259,
"responseCode": {
"code": 200,
"name": "OK"
},
"tests": {},
"testPassFailCounts": {},
"times": [
259
],
"allTests": [
{}
]
},
{
"id": "e80d222f-89fe-45cd-a139-6d1b0cfafece",
"name": "Session summary2",
"url": "https://a.blazemeter.com/api/v4/tests/9595495/sessions-summaries",
"time": 442,
"responseCode": {
"code": 200,
"name": "OK"
},
"tests": {},
"testPassFailCounts": {},
"times": [
442
],
"allTests": [
{}
]
},
{
"id": "4b129897-0241-465b-94dc-29814808442e",
"name": "Session summary3",
"url": "https://a.blazemeter.com/api/v4/tests/9595540/sessions-summaries",
"time": 319,
"responseCode": {
"code": 200,
"name": "OK"
},
"tests": {},
"testPassFailCounts": {},
"times": [
319
],
"allTests": [
{}
]
},
{
"id": "bd17cd20-7165-48e0-8a03-c2d95affc4d1",
"name": "Session summary4",
"url": "https://a.blazemeter.com/api/v4/tests/9595539/sessions-summaries",
"time": 593,
"responseCode": {
"code": 200,
"name": "OK"
},
"tests": {},
"testPassFailCounts": {},
"times": [
593
],
"allTests": [
{}
]
},
{
"id": "557c971f-f918-49f1-9d69-7c9547bfe504",
"name": "Session summary5",
"url": "https://a.blazemeter.com/api/v4/tests/9595355/sessions-summaries",
"time": 337,
"responseCode": {
"code": 200,
"name": "OK"
},
"tests": {},
"testPassFailCounts": {},
"times": [
337
],
"allTests": [
{}
]
},
{
"id": "8dd94fcc-d04c-43ac-9793-ba0351a41a9d",
"name": "Get master id",
"url": "https://a.blazemeter.com/api/v4/sessions/r-sg-60dc87126dd20190458039",
"time": 259,
"responseCode": {
"code": 200,
"name": "OK"
},
"tests": {},
"testPassFailCounts": {},
"times": [
259
],
"allTests": [
{}
]
},
{
"id": "201bd700-de90-45b7-83f6-06b8c7322727",
"name": "See the masters test",
"url": "https://a.blazemeter.com/api/v4/masters/35589479",
"time": 284,
"responseCode": {
"code": 200,
"name": "OK"
},
"tests": {
"TestOnBlazemeterWasBroken": true
},
"testPassFailCounts": {
"TestOnBlazemeterWasBroken": {
"pass": 1,
"fail": 0
}
},
"times": [
284
],
"allTests": [
{
"TestOnBlazemeterWasBroken": true
}
]
}
],
"count": 1,
"totalTime": 3609,
"collection": {
"requests": [
{
"id": "bb1b9473-2f66-4153-8996-88cf40715ba6",
"method": "GET"
},
{
"id": "c694f16e-8195-4696-a874-fdaed51bbfd7",
"method": "GET"
},
{
"id": "e80d222f-89fe-45cd-a139-6d1b0cfafece",
"method": "GET"
},
{
"id": "4b129897-0241-465b-94dc-29814808442e",
"method": "GET"
},
{
"id": "bd17cd20-7165-48e0-8a03-c2d95affc4d1",
"method": "GET"
},
{
"id": "557c971f-f918-49f1-9d69-7c9547bfe504",
"method": "GET"
},
{
"id": "8dd94fcc-d04c-43ac-9793-ba0351a41a9d",
"method": "GET"
},
{
"id": "201bd700-de90-45b7-83f6-06b8c7322727",
"method": "GET"
}
]
}
}
The part I'm looking for is "allTests": [{"TestOnBlazemeterWasBroken": true}] how could I find this value and check if it is there and if it equals to true.
{
"id": "201bd700-de90-45b7-83f6-06b8c7322727",
"name": "See the masters test",
"url": "https://a.blazemeter.com/api/v4/masters/35589479",
"time": 284,
"responseCode": {
"code": 200,
"name": "OK"
},
"tests": {
"TestOnBlazemeterWasBroken": true
},
"testPassFailCounts": {
"TestOnBlazemeterWasBroken": {
"pass": 1,
"fail": 0
}
},
"times": [
284
],
"allTests": [
{
"TestOnBlazemeterWasBroken": true
}
]
}
I have tried this but it didn't work - and I get this error:
Fatal error: Uncaught TypeError: Cannot access offset of type string on string in C:\xampp\htdocs\index.php:11 Stack trace: #0 {main} thrown in C:\xampp\htdocs\index.php on line 11
Code:
<?php
// Read JSON file
$json = file_get_contents('Testing.postman_test_run.json');
//Decode JSON
$json_data = json_decode($json,true);
//Traverse array and get the data for students aged less than 20
foreach ($json_data as $key1 => $value1) {
if($json_data[$key1]["allTests"][7]['TestOnBlazemeterWasBroken'] == true){
print_r($json_data[$key1]);
}
}
?>

The following ought to work OK whether there is one or more results.
$str='{
"id": "311e6d5a-3f20-42d2-b276-80c5f33f1d7f",
"name": "Testing",
"timestamp": "2021-07-02T10:39:48.544Z",
"collection_id": "6cd6e3b9-cce9-4746-83ca-9349708d3b18",
"folder_id": 0,
"environment_id": "db26e19d-4373-4004-9ad2-348545c6f521",
"totalPass": 1,
"totalFail": 0,
"results": [
{
"id": "bb1b9473-2f66-4153-8996-88cf40715ba6",
"name": "retrieving IDs",
"url": "https://a.blazemeter.com/api/v4/tests?workspaceId=894576&limit=20&hasExecutions=true&filterByActivePlatform=false",
"time": 1116,
"responseCode": {
"code": 200,
"name": "OK"
},
"tests": {},
"testPassFailCounts": {},
"times": [
1116
],
"allTests": [
{}
]
},
{
"id": "201bd700-de90-45b7-83f6-06b8c7322727",
"name": "See the masters test",
"url": "https://a.blazemeter.com/api/v4/masters/35589479",
"time": 284,
"responseCode": {
"code": 200,
"name": "OK"
},
"tests": {
"TestOnBlazemeterWasBroken": true
},
"testPassFailCounts": {
"TestOnBlazemeterWasBroken": {
"pass": 1,
"fail": 0
}
},
"times": [
284
],
"allTests": [
{
"TestOnBlazemeterWasBroken": true
}
]
}
]
}';
$fail=false;
$testname='TestOnBlazemeterWasBroken';
$json=json_decode( $str );
$results=$json->results ?: false;
if( $results ){
foreach( $results as $result ){
if( property_exists( $result, 'allTests' ) ){
foreach( $result->allTests as $test ){
if( property_exists( $test, $testname ) && $test->$testname==true ){
$fail=true;
break 2;
}
}
}
}
}
$status=$fail ? 'Failed! ' : 'Passed!';
printf( 'The test "%s" was %s', $testname, $status );
Given the above $str data this will yield "The test "TestOnBlazemeterWasBroken" was Failed!" because within one of the results the specific test was found and evaluated to true.
Given the source data ( saved as blaze-test.json )
{
"id": "311e6d5a-3f20-42d2-b276-80c5f33f1d7f",
"name": "Testing",
"timestamp": "2021-07-02T10:39:48.544Z",
"collection_id": "6cd6e3b9-cce9-4746-83ca-9349708d3b18",
"folder_id": 0,
"environment_id": "db26e19d-4373-4004-9ad2-348545c6f521",
"totalPass": 1,
"totalFail": 0,
"results": [
{
"id": "bb1b9473-2f66-4153-8996-88cf40715ba6",
"name": "retrieving ID's",
"url": "https://a.blazemeter.com/api/v4/tests?workspaceId=894576&limit=20&hasExecutions=true&filterByActivePlatform=false",
"time": 1116,
"responseCode": {
"code": 200,
"name": "OK"
},
"tests": {},
"testPassFailCounts": {},
"times": [
1116
],
"allTests": [
{}
]
},
{
"id": "c694f16e-8195-4696-a874-fdaed51bbfd7",
"name": "Session summary1",
"url": "https://a.blazemeter.com/api/v4/tests/9661550/sessions-summaries",
"time": 259,
"responseCode": {
"code": 200,
"name": "OK"
},
"tests": {},
"testPassFailCounts": {},
"times": [
259
],
"allTests": [
{}
]
},
{
"id": "e80d222f-89fe-45cd-a139-6d1b0cfafece",
"name": "Session summary2",
"url": "https://a.blazemeter.com/api/v4/tests/9595495/sessions-summaries",
"time": 442,
"responseCode": {
"code": 200,
"name": "OK"
},
"tests": {},
"testPassFailCounts": {},
"times": [
442
],
"allTests": [
{}
]
},
{
"id": "4b129897-0241-465b-94dc-29814808442e",
"name": "Session summary3",
"url": "https://a.blazemeter.com/api/v4/tests/9595540/sessions-summaries",
"time": 319,
"responseCode": {
"code": 200,
"name": "OK"
},
"tests": {},
"testPassFailCounts": {},
"times": [
319
],
"allTests": [
{}
]
},
{
"id": "bd17cd20-7165-48e0-8a03-c2d95affc4d1",
"name": "Session summary4",
"url": "https://a.blazemeter.com/api/v4/tests/9595539/sessions-summaries",
"time": 593,
"responseCode": {
"code": 200,
"name": "OK"
},
"tests": {},
"testPassFailCounts": {},
"times": [
593
],
"allTests": [
{}
]
},
{
"id": "557c971f-f918-49f1-9d69-7c9547bfe504",
"name": "Session summary5",
"url": "https://a.blazemeter.com/api/v4/tests/9595355/sessions-summaries",
"time": 337,
"responseCode": {
"code": 200,
"name": "OK"
},
"tests": {},
"testPassFailCounts": {},
"times": [
337
],
"allTests": [
{}
]
},
{
"id": "8dd94fcc-d04c-43ac-9793-ba0351a41a9d",
"name": "Get master id",
"url": "https://a.blazemeter.com/api/v4/sessions/r-sg-60dc87126dd20190458039",
"time": 259,
"responseCode": {
"code": 200,
"name": "OK"
},
"tests": {},
"testPassFailCounts": {},
"times": [
259
],
"allTests": [
{}
]
},
{
"id": "201bd700-de90-45b7-83f6-06b8c7322727",
"name": "See the masters test",
"url": "https://a.blazemeter.com/api/v4/masters/35589479",
"time": 284,
"responseCode": {
"code": 200,
"name": "OK"
},
"tests": {
"TestOnBlazemeterWasBroken": true
},
"testPassFailCounts": {
"TestOnBlazemeterWasBroken": {
"pass": 1,
"fail": 0
}
},
"times": [
284
],
"allTests": [
{
"TestOnBlazemeterWasBroken": true
}
]
}
],
"count": 1,
"totalTime": 3609,
"collection": {
"requests": [
{
"id": "bb1b9473-2f66-4153-8996-88cf40715ba6",
"method": "GET"
},
{
"id": "c694f16e-8195-4696-a874-fdaed51bbfd7",
"method": "GET"
},
{
"id": "e80d222f-89fe-45cd-a139-6d1b0cfafece",
"method": "GET"
},
{
"id": "4b129897-0241-465b-94dc-29814808442e",
"method": "GET"
},
{
"id": "bd17cd20-7165-48e0-8a03-c2d95affc4d1",
"method": "GET"
},
{
"id": "557c971f-f918-49f1-9d69-7c9547bfe504",
"method": "GET"
},
{
"id": "8dd94fcc-d04c-43ac-9793-ba0351a41a9d",
"method": "GET"
},
{
"id": "201bd700-de90-45b7-83f6-06b8c7322727",
"method": "GET"
}
]
}
}
The processing script:
// Fetch the data from local file in same directory
$str=file_get_contents( __DIR__ . '/blaze-test.json' );
// set the test and result status default - assume pass unless specific fail
$fail=false;
$testname='TestOnBlazemeterWasBroken';
// decode the string data so we can work with it
$json=json_decode( $str );
$results=$json->results ?: false;
if( $results ){
//iterate through the results
foreach( $results as $result ){
$name=$result->name;
$code=$result->responseCode->code;
if( property_exists( $result, 'allTests' ) ){
foreach( $result->allTests as $test ){
// does the test exist in the data and was it failed?
if( property_exists( $test, $testname ) && $test->$testname==true ){
$fail=true;
break 2;
}
}
}
}
$status=$fail ? 'Failed' : 'Passed';
printf(
'
<style>
.Failed{color:red}
.Passed{color:green}
</style>
<h2>Tests run: %d</h2>
<p>The test "%s" within "%s" was <span class="%s">%s</span> with code %s!</p>',
count($results),
$testname,
$name,
$status,
$status,
$code
);
}
The result:
Tests run: 8
The test "TestOnBlazemeterWasBroken" within "See the masters test" was Failed with code 200!

You need to look at your data.
First (if you do not see it in json) you may look at the array.
So just print it (f.e. echo var_export($json_data, true) . PHP_EOL; die;)
or write it into an file.
Looks ok? Then build the loop.
First you loop through the array at the result offset.
And if you do not know what you get on one result then do the same as previously: look at it. Print it.
Same for any deeper loops.
The loop:
// Read JSON file
$json = file_get_contents('Testing.postman_test_run.json');
//Decode JSON
$json_data = json_decode($json, true);
//Traverse array and get the data for students aged less than 20
foreach ($json_data['results'] as $result) {
foreach ($result["allTests"] as $test) {
if (isset($test['TestOnBlazemeterWasBroken'])
and $test['TestOnBlazemeterWasBroken'] === true
) {
// You found it and its true.
echo "TestOnBlazemeterWasBroken is true at {$result['id']}\r\n";
// May collect or print or w/e.
}
}
}

Related

Compare 2 Multidimensional Arrays in PHP and show all the difference in an array

I have 2 Multiple-Arrays and I want to compare them. In the second Array I want then show with colors which value has changed, which key is new and which key is removed.
I have found a lot of different solutions, but no one function for me.
Here are my arrays:
{
"originFormation": {
"stationName": "Bern",
"sections": [{
"name": "B",
"cars": [{
"type": "LOK",
"occupancy": "UNKNOWN",
"attributes": [],
"closed": false,
"previousPassage": false,
"nextPassage": false
}]
}, {
"name": "C",
"cars": [{
"type": "CAR",
"number": "1",
"class": "1",
"occupancy": "UNKNOWN",
"attributes": ["AbteilRollstuhl", "AbteilBusiness"],
"closed": false,
"previousPassage": false,
"nextPassage": true
}, {
"type": "CAR",
"number": "1",
"class": "2",
"occupancy": "UNKNOWN",
"attributes": [],
"closed": false,
"previousPassage": true,
"nextPassage": true
}]
}],
"legendItems": [{
"id": "1",
"text": "1st class coach",
"refersTo": "type"
}, {
"id": "2",
"text": "2st class coach",
"refersTo": "type"
}, {
"id": "Fahrtrichtung",
"text": "Direction of travel",
"refersTo": "code"
}, {
"id": "FA",
"text": "Family Coach with play area",
"refersTo": "type"
}, {
"id": "AbteilRollstuhl",
"text": "Wheelchair space",
"refersTo": "code"
}, {
"id": "AbteilVeloPl",
"text": "Bicycle loading: Without reservation",
"refersTo": "code"
}, {
"id": "LK",
"text": "Locomotive",
"refersTo": "type"
}, {
"id": "WR",
"text": "Restaurant 1st and 2nd class",
"refersTo": "type"
}, {
"id": "AbteilBusiness",
"text": "Business zone in 1st class: Reservation possible",
"refersTo": "code"
},
{
"id": "HFS_WG_NUM",
"text": "Coach",
"refersTo": "code"
}, {
"id": "KD",
"text": "No passage",
"refersTo": "type"
}
],
"info": {
"title": "Changes to the composition of the train",
"formationChanges": []
}
}
}
Array2:
{
"originFormation": {
"stationName": "Bern",
"sections": [
{
"name": "B",
"cars": [
{
"type": "LOK",
"occupancy": "UNKNOWN",
"attributes": [],
"closed": false,
"previousPassage": false,
"nextPassage": false
}
]
},
{
"name": "C",
"cars": [
{
"type": "CAR",
"number": "12",
"class": "1",
"occupancy": "UNKNOWN",
"attributes": [
"AbteilRollstuhl",
"AbteilBusiness"
],
"closed": false,
"previousPassage": false,
"nextPassage": true
},
{
"type": "CAR",
"number": "1",
"class": "2",
"occupancy": "UNKNOWN",
"attributes": [
"AbteilStefan"
],
"closed": false,
"previousPassage": true,
"nextPassage": true
},
{
"type": "CAR",
"number": "2",
"class": "1",
"occupancy": "UNKNOWN",
"attributes": [],
"closed": false,
"previousPassage": true,
"nextPassage": true
}
]
}
],
"legendItems": [
{
"id": "1",
"text": "1st class coach",
"refersTo": "type"
},
{
"id": "2",
"text": "2st class coach",
"refersTo": "type"
},
{
"id": "Fahrtrichtung",
"text": "Direction of travel",
"refersTo": "code"
},
{
"id": "FA",
"text": "Family Coach with play area",
"refersTo": "type"
},
{
"id": "AbteilRollstuhl",
"text": "Wheelchair space",
"refersTo": "code"
},
{
"id": "AbteilVeloPl",
"text": "Bicycle loading: Without reservation",
"refersTo": "code"
},
{
"id": "LK",
"text": "Locomotive",
"refersTo": "type"
},
{
"id": "WR",
"text": "Restaurant 1st and 2nd class",
"refersTo": "type"
},
{
"id": "AbteilBusiness",
"text": "Business zone in 1st class: Reservation possible",
"refersTo": "code"
},
{
"id": "AbteilStefan",
"text": "Ich bin ein neues Abteil",
"refersTo": "code"
},
{
"id": "HFS_WG_NUM",
"text": "Coach",
"refersTo": "code"
},
{
"id": "KD",
"text": "No passage",
"refersTo": "type"
}
],
"info": {
"title": "Changes to the composition of the train",
"formationChanges": [
"All Changed"
]
}
}
}
My fonction to compare:
function array_diff_assoc_recursive($array1, $array2)
{
foreach($array1 as $key => $value)
{
if(is_array($value))
{
if(!isset($array2[$key]))
{
$difference[$key] = $value;
}
elseif(!is_array($array2[$key]))
{
$difference[$key] = "<b>".$value."</b>";
}
else
{
$new_diff = array_diff_assoc_recursive($value, $array2[$key]);
if($new_diff != FALSE)
{
$difference[$key] = $new_diff;
}
}
}
elseif(!isset($array2[$key]) || $array2[$key] != $value)
{
$difference[$key] = "<b>".$value."</b>";
}
}
return !isset($difference) ? 0 : $difference;
}
var_dump(array_diff_assoc_recursive($array2, $array1));
This difference i get:
[originformation][sections][1][cars][0][number] -> newValue 12
[originformation][sections][1][cars][1][attributes] -> newValue AbteilStefan
[originformation][sections][1][cars][2] -> all Attributes are new
[originformation][legendItems][9][id] -> newValue AbteilStefan
[originformation][legendItems][9][text] -> newValue Ich bin ein neues Abteil
[originformation][legendItems][10] -> all Attributes are new
[originformation][legendItems][11] -> all Attributes are new
[originformation][info][formationChanges][0] => newValue All Changed
The difference i expected
[originformation][sections][1][cars][0][number] -> newValue 12
[originformation][sections][1][cars][1] -> all Attributes are new
[originformation][legendItems][9] -> all Attributes are new
[originformation][info][formationChanges][0] => newValue All Changed
Problem
My function doesn't see, that car in Array2 I put in a complete new car and also a complete new legendItem and the rest is still the same.
Does someone know how I can compare the arrays, that he doesn't check the order of the attributes on the same level?

Elasticsearch batch not indexing all items using PHP client

I've been trying to build an index in ES and add the initial items to it (around 350k), using PHP.
I tried all kinds of batch sizes (from 10 items to 1k), check the count, check the threshold, but for some reason it doesn't index every item.
It just skips over some random items, without any errors in the batch result response. I feel like I tried everything and I have to idea what to do next
I'm using Amazon OpenSearch with the latest supported ES (7.10).
The index looks like this:
{
"wonder-search": {
"aliases": {},
"mappings": {
"properties": {
"address": {
"type": "text"
},
"city": {
"type": "text"
},
"city_id": {
"type": "integer"
},
"duration": {
"type": "integer"
},
"filename": {
"type": "text"
},
"geo_point": {
"type": "geo_point"
},
"icon": {
"type": "keyword"
},
"is_sandbox": {
"type": "integer"
},
"item_id": {
"type": "integer"
},
"item_label": {
"type": "keyword"
},
"latitude": {
"type": "float"
},
"longitude": {
"type": "float"
},
"search_text_caption_json": {
"type": "text",
"index_phrases": true
},
"search_text_city_json": {
"type": "text",
"index_phrases": true
},
"search_text_completion": {
"type": "completion",
"analyzer": "simple",
"preserve_separators": true,
"preserve_position_increments": true,
"max_input_length": 50,
"contexts": [
{
"name": "type",
"type": "CATEGORY"
}
]
},
"search_text_country_json": {
"type": "text",
"index_phrases": true
},
"search_text_cuisine_name_json": {
"type": "text",
"index_phrases": true
},
"search_text_location_name_json": {
"type": "text",
"index_phrases": true
},
"search_text_state_json": {
"type": "text",
"index_phrases": true
},
"search_text_tag_name_json": {
"type": "text",
"index_phrases": true
},
"search_text_username_json": {
"type": "text",
"index_phrases": true
},
"sort": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"sort_score": {
"type": "double"
},
"type": {
"type": "text"
},
"user_icon": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"user_id": {
"type": "integer"
},
"username": {
"type": "keyword"
},
"vanity_url": {
"type": "keyword"
},
"video_count": {
"type": "integer"
}
}
},
"settings": {
"index": {
"routing": {
"allocation": {
"include": {
"_tier_preference": "data_content"
}
}
},
"mapping": {
"ignore_malformed": "true"
},
"number_of_shards": "1",
"provided_name": "wonder-search",
"creation_date": "1671003076106",
"number_of_replicas": "1",
"uuid": "YQh1q40WTneLE4MWDWhArw",
"version": {
"created": "7100199"
}
}
}
}
}
and one item looks like this:
{
"_index": "wonder-search",
"_type": "_doc",
"_id": "wq2LD4UBUAuy7FQPhtZh",
"_version": 1,
"_seq_no": 2003,
"_primary_term": 1,
"found": true,
"_source": {
"sort": "4004",
"item_id": "4934",
"user_id": "434",
"user_icon": "/site-content/avatars/Sp8AXjTJvMbRao2oZbuiUuSVH042-1597776099045.jpeg",
"username": "chuurros",
"item_label": "Kyoto Katsugyu【京都勝牛】",
"search_text_username_json": [
"chuurros"
],
"search_text_caption_json": [
"Absolutely love their gyukatsu (beef katsu) here! Delicious and will keep you wanting more! 🥰"
],
"search_text_city_json": [
"Toronto"
],
"search_text_state_json": [
"Ontario"
],
"search_text_country_json": [
"Canada"
],
"search_text_location_name_json": [
"Kyoto Katsugyu【京都勝牛】"
],
"search_text_tag_name_json": [
"japanese",
"restaurant",
"asian",
"dining",
"topcollection-4934"
],
"search_text_cuisine_name_json": [],
"type": "video",
"vanity_url": "",
"icon": "",
"city": "Toronto",
"city_id": "439",
"latitude": "43.65682410",
"longitude": "-79.37617410",
"address": "134 Dundas St E",
"duration": "9.57",
"video_count": "0",
"sort_score": "43",
"filename": "373d75fd-4292-4e5b-a239-4b1c39ffc86c.MOV",
"is_sandbox": "0",
"geo_point": {
"lat": "43.65682410",
"lon": "-79.37617410"
},
"search_text_completion": {
"input": [
"Kyoto Katsugyu【京都勝牛】"
],
"contexts": {
"type": [
"video"
]
}
}
}
}
Any ideas why does it work like this?

How to read Specific value from curl Response

this is my response
i need to read first line id value & url of sandbox
{
"id": "chg_g5Y25220190539Ob590811651",
"object": "charge",
"live_mode": false,
"api_version": "V2",
"method": "CREATE",
"status": "INITIATED",
"amount": 1.000,
"currency": "KWD",
"threeDSecure": false,
"card_threeDSecure": false,
"save_card": false,
"statement_descriptor": "Sample",
"description": "Test DESC",
"transaction":
{
"timezone": "UTC+03:00",
"created": "1573191592651",
"url": "https://sandbox.payments.tap.company/test_gosell/v2/payment/response.aspx?tap_chg=PsV8hZdr78kEIAOZl9XL1B5u3dXe%2bBQ%2b3Hrd%2fempxYs%3d&sess=noWi606EI%2bM%3d&token=PsV8hZdr78kEIAOZl9XL1B5u3dXe%2bBQ%2bTyYdQy9iGpS6aAXwKOqAdw%3d%3d",
"expiry": { "period": 30, "type": "MINUTE" },
"asynchronous": false
},
"reference": { "transaction": "txn_0001", "order": "ord_0001" },
"response": { "code": "100", "message": "Initiated" },
"receipt": { "email": true, "sms": true },
"customer": { "first_name": "yxy", "last_name": "ttt", "email": "xyx#xyz.com" },
"source": { "object": "source", "id": "src_card" },
"redirect": { "status": "PENDING", "url": "http://localhost:81/School/" },
"post": { "status": "PENDING", "url": "http://localhost:81/School/" } }
assuming you have your response from curl in a variable called $resp
$resp_decoded = json_decode($resp,TRUE);
print($resp_decoded['id']);
print($resp_decoded['transaction']['url']);

How to JSON with duplicate 'id' values?

I am receiving data from another site with json API.
how can I get the data of the objects with the same id number.
I try as follows but it turns blank..
there are 10 objects with the same id number
how can i get them.
The typeid number is the same but the specialvalue value is different.
{"id":4620041,"active":true,"typeid":56,"specialvalue":"0.5","fields":{"magic":{"active":true,"type":"magic","value":"1.05"},"xmagic":{"active":true,"type":"xmagic","value":"7.5"}}}
{"id":4620045,"active":true,"typeid":56,"specialvalue":"1.5","fields":{"magic":{"active":true,"type":"magic","value":"3.05"},"xmagic":{"active":true,"type":"xmagic","value":"3.5"}}}
if($test->typeid =="56")
{
if (specialvalue == "0.5") {
$alta = $test->fields->magic->value;
$uste = $test->fields->xmagic->value;
}
}
echo $alta - $uste ;
Thank you in advance for your help
https://i.hizliresim.com/Pl0LL7.jpg
Few observations :
Provided JSON is not a valid JSON.
It should be an array of objects to filter the specific data as per the requirement.
Solution :
let jsonObj = [{
"id": 5246752,
"active": true,
"typeid": 56,
"specialvalue": "0.5",
"fields": {
"magic": {
"active": true,
"type": "magic",
"value": "1.06"
},
"xmagic": {
"active": true,
"type": "xmagic",
"value": "7.0"
}
}
}, {
"id": 5246753,
"active": true,
"typeid": 56,
"specialvalue": "1.5",
"fields": {
"magic": {
"active": true,
"type": "magic",
"value": "1.35"
},
"xmagic": {
"active": true,
"type": "xmagic",
"value": "3.0"
}
}
}, {
"id": 5246754,
"active": true,
"typeid": 56,
"specialvalue": "2.5",
"fields": {
"magic": {
"active": true,
"type": "magic",
"value": "2.0"
},
"xmagic": {
"active": true,
"type": "xmagic",
"value": "1.7"
}
}
}, {
"id": 5246755,
"active": true,
"typeid": 56,
"specialvalue": "3.5",
"fields": {
"magic": {
"active": true,
"type": "magic",
"value": "3.45"
},
"xmagic": {
"active": true,
"type": "xmagic",
"value": "1.25"
}
}
}, {
"id": 5246756,
"active": true,
"typeid": 56,
"specialvalue": "4.5",
"fields": {
"magic": {
"active": true,
"type": "magic",
"value": "6.25"
},
"xmagic": {
"active": true,
"type": "xmagic",
"value": "1.08"
}
}
}, {
"id": 5246757,
"active": true,
"typeid": 56,
"specialvalue": "5.5",
"fields": {
"magic": {
"active": true,
"type": "magic",
"value": "9.5"
},
"xmagic": {
"active": true,
"type": "xmagic",
"value": "1.02"
}
}
}];
let filteredData = jsonObj.filter(item => item.typeid===56 && item.specialvalue==="0.5");
console.log(filteredData);
Use .filter
var filteredData = data.filter(
(el) => {
return el.typeid===56 && el.specialvalue==="0.5";
}
);
This will return only those elements with el.typeid===56 && specialvalue==="0.5"

How to not display information if it exists in one of two arrays

The situation is I have two arrays that is collecting JSON data via the API :
$players = getAPI("http://xx.xxx.xxx.xx:xxxxx/players.json?apiKey=xxxxxxxxxxxxxxxxxxxxxxxx");
$recents = getAPI("xx.xxx.xxx.xx:xxxxx/recent.json?apiKey=xxxxxxxxxxxxxxxxxxxxxxxx");
The method is getting the contents and decoding the JSON into an array.
For the players array we have this data in an array:
$players
[
{
"id": "76561198033377272",
"name": "PitMonk",
"position": {
"x": -339,
"y": 26,
"z": 191
},
"rotation": 128,
"time": 418310,
"ip": "",
"inventory": {
"main": [],
"belt": [
{
"name": "rock",
"amount": 1,
"blueprint": false,
"condition": 100
},
{
"name": "torch",
"amount": 1,
"blueprint": false,
"condition": 100
}
],
"wear": []
}
},
{
"id": "76561198088638439",
"name": "Pippa",
"position": {
"x": -337,
"y": 25,
"z": 177
},
"rotation": 73,
"time": 419136,
"ip": "",
"inventory": {
"main": [
{
"name": "arrow.wooden",
"amount": 12,
"blueprint": false
},
{
"name": "bow.hunting",
"amount": 1,
"blueprint": false,
"condition": 93
},
{
"name": "blueprint_fragment",
"amount": 25,
"blueprint": false
},
{
"name": "metal.fragments",
"amount": 1366,
"blueprint": false
},
{
"name": "metal.refined",
"amount": 48,
"blueprint": false
},
{
"name": "charcoal",
"amount": 1120,
"blueprint": false
},
{
"name": "lowgradefuel",
"amount": 738,
"blueprint": false
}
],
"belt": [
{
"name": "rock",
"amount": 1,
"blueprint": false,
"condition": 100
},
{
"name": "torch",
"amount": 1,
"blueprint": false,
"condition": 100
},
{
"name": "pickaxe",
"amount": 1,
"blueprint": false,
"condition": 76
},
{
"name": "pickaxe",
"amount": 1,
"blueprint": false,
"condition": 17
},
{
"name": "pickaxe",
"amount": 1,
"blueprint": false,
"condition": 100
},
{
"name": "pickaxe",
"amount": 1,
"blueprint": false,
"condition": 100
}
],
"wear": [
{
"name": "burlap.shirt",
"amount": 1,
"blueprint": false
},
{
"name": "attire.hide.skirt",
"amount": 1,
"blueprint": false
}
]
}
}
]
$recents
[
{
"id": "76561198039206786",
"name": "JakeGroves"
},
{
"id": "76561198088638439",
"name": "Pippa"
},
{
"id": "76561198033377272",
"name": "PitMonk"
},
{
"id": "76561198146864439",
"name": "YepWellDone"
},
{
"id": "76561198164836207",
"name": "Baz"
},
{
"id": "76561198076406281",
"name": "xwalnutx"
},
{
"id": "76561197985716090",
"name": "Darkflame134"
},
{
"id": "76561198263423842",
"name": "XitaikiznerX"
},
{
"id": "76561198129952244",
"name": "NatanGamer"
},
{
"id": "76561198071842055",
"name": "Baha Bey"
}
]
As you can see the players is the people connected, and recents is the total list of people who have connected recently.
I have attempted this:
foreach ($players as $player) {
echo $players->name;
}
echo "</br></br>";
foreach ($recent as $rec) {
if ($rec->name != $player->name) {
echo $rec->name . "</br>";
}
}
and it produces the result:
PitMonk Pippa
JakeGroves
PitMonk
YepWellDone
Baz
xwalnutx
Darkflame134
XitaikiznerX
NatanGamer
Baha Bey
So it is only ignoring 'pippa', I am not sure if it is possible to interact with two arrays as such for unique values?
You are interested in listing all names out of $users which don't exist in $players or $recents, right?
Assuming you are only interested in the name:
// First, let's get a new array with all names from both arrays (can contain dups)
$pcNames = array_map($players + $recents, function($playerObject) {
return $playerObject->name;
});
// Next, let's remove all dups
$pcNames = array_unique($pcNames);
// === At this point you have an array with all names from `$players` and `$recents` ===
// === You may do something else with those, but I'll now create another array with ===
// === all users not in the players/recents lists. ===
// Now let's also get a list of names of users in the `$users` variable
$userNames = array_map($users, function($playerObject) {
return $playerObject->name;
});
// And finally let's get all names which are not in players or recents
$diffNames = array_diff($userNames, $pcNames);
// Let's output those to see whether it worked
var_dump($diffNames);
Of course there are other ways depending on your use case. We could for example extract the names of all three arrays and then just use array_diff with 3 arguments (but then you don't have the $pcArray side product), or if you actually want to compare IDs but print names, we would have to change all the inline functions to extract ID instead of name and further down reference the users array to get the actual name, etc.

Categories