Count amount of elements from nested array - php

In the for loop I am trying to count the amount of flights in a nested array decoded from a JSON feed. Unfortunately it only shows 2 flights, when more flights are available. What am I doing wrong?
Json feed example from endpoint
{
"response": [
{
"flight": {
"number": "6204",
"iata_number": "HV6204",
"icao_number": "TRA6204"
}
},
{
"flight": {
"number": "7012",
"iata_number": "TB7012",
"icao_number": "JAF7012"
}
},
{
"flight": {
"number": "6652",
"iata_number": "HV6652",
"icao_number": "TRA6652"
}
},
{
"flight": {
"number": "1925",
"iata_number": "W61925",
"icao_number": "WZZ1925"
}
},
{
"flight": {
"number": "5075",
"iata_number": "W65075",
"icao_number": "WZZ5075"
}
},
{
"flight": {
"number": "4289",
"iata_number": "W64289",
"icao_number": "WZZ4289"
}
},
{
"flight": {
"number": "7861",
"iata_number": "W67861",
"icao_number": "WZZ7861"
}
},
{
"flight": {
"number": "3066",
"iata_number": "FR3066",
"icao_number": "RYR3066"
}
}
]
} .
The PHP code example
<?php
$url = 'https://api.endpoint'; // path to JSON file
$data = file_get_contents($url);
$flights = json_decode($data, true);
for($i=0; $i<=count($flights['response'][0]['flight']['iata_number']); $i++) {
echo "Flightnumber" . $flights['response'][$i]['flight']["iata_number"] . '<br/>';
}
?>
Any help is very appreciated

What really should be used here is foreach. With foreach you don't have to care about count() of your array:
$url = 'https://api.endpoint'; // path to JSON file
$data = file_get_contents($url);
$flights = json_decode($data, true);
foreach ($flights['response'] as $item) {
echo $item['flight']['iata_number'] . '<br />';
}
Simple demo is here.
If you still want to use for-loop, it should look like:
for ($i = 0; $i < count($flights['response']); $i++) {
echo $flights['response'][$i]['flight']['iata_number'] . '<br />';
}

for($i=0; $i<count($flights['response'][0]['flight']['iata_number']); $i++) {
echo "Flightnumber" . $flights['response'][$i]['flight']["iata_number"] . '<br/>';
}
count($flights['response'][0]['flight']['iata_number']) is always going to equal one, so you're only looping twice as would be expected (two flights). My guess is that's supposed to be count($flights['response']) or something similar.

You can use array_walk_recursive
array_walk_recursive($jarr, function($v, $k) use (&$flights){
if($k == 'iata_number') $flights[] = $v;
});
Live example :- https://3v4l.org/5Rp9K

Related

Access variable Array Data PHP

i have the following Array Structure from Facebook Graph API response.
"data": [
{
"actions": [
{
"action_type": "comment",
"value": "2"
},
{
"action_type": "offsite_conversion",
"value": "1606"
}
],
"date_start": "2017-04-03",
"date_stop": "2017-05-02"
},
{
"actions": [
{
"action_type": "post",
"value": "2"
},
{
"action_type": "post_reaction",
"value": "33"
},
{
"action_type": "page_engagement",
"value": "816"
},
{
"action_type": "post_engagement",
"value": "807"
},
{
"action_type": "offsite_conversion",
"value": "1523"
}
],
"date_start": "2017-04-03",
"date_stop": "2017-05-02"
},
]
The Number of values is flexible and i want to get the value from "offsite_conversion". Normally i would do it for example like that:
data['data'][0]['actions']['1']['value']
But in that case this doesn't work because ['1'] is variable.
Use a loop and test the action type.
foreach ($data['data'][0]['actions'] as $action) {
if ($action['action_type'] == 'offsite_conversion') {
$result = $data['value'];
break;
}
}
because "offsite_conversions" is always the last
If $data['data'][0]['actions'][LAST VALUE]['value'] is what you're looking for:
Your idea of counting should work then:
$actions = $data['data'][0]['actions'];
$index = count($actions) - 1;
$value = $actions[$index]['value'];
So not completely clear what are you trying to achieve, but in a simple way you can just iterate over your $data array:
$needed_values = array();
foreach ($data['data'] as $item) {
foreach ($item['actions'] as $action) {
if ($action['action_type'] == 'offsite_conversion') {
$needed_values[] = $action['value'];
}
}
}
Barmar has the best approach if you don't know where it is, but it's much easier if you want the last one:
$result = end($data['data'][0]['actions'])['value'];
Pretend $json holds the data from facebook
<?php
$data = json_decode($json);
$conversions = 0;
foreach ($data as $datum) {
foreach ($datum['actions'] as $action) {
if ($action['action_type'] === 'offsite_convserion') {
$conversions += (int)$action['value'];
break;
}
}
}

Search in array in json file

I have an array which has a key with multiple content. I want to get that array which includes the key that I search .
$arr = json_decode('{"people":[
{
"id": "8080",
"content": "foo",
"member": [123, 456],
"interval": 7
},
{
"id": "8097",
"content": "bar",
"member": [1234, 4567],
"interval": 7
}
]}', true);
$results = array_filter($arr['people'], function($people) {
return $people['id'] == 8080;
});
echo json_encode($results);
This will return:
{"id":"8080","content":"foo","member":[123,456],"interval":7}
I want that:
$results = array_filter($arr['people'], function($people) {
return $people['member'] == 123;
});
And this does not work.
Have somebody an idea?
As #JonStirling said in comment. Use in_array() function.
$arr = json_decode('{"people":[
{
"id": "8080",
"content": "foo",
"member": [123, 456],
"interval": 7
},
{
"id": "8097",
"content": "bar",
"member": [1234, 4567],
"interval": 7
}
]}', true);
$searchId = 123;
$results = array_filter($arr['people'], function($people) use ($searchId) {
return in_array($searchId, $people['member']);
});
echo json_encode($results);
Result:
[{"id":"8080","content":"foo","member":[123,456],"interval":7}]
See if this helps:
$arr = json_decode('{"people":[
{
"id": "8080",
"content": "foo",
"member": [123, 456],
"interval": 7
},
{
"id": "8097",
"content": "bar",
"member": [1234, 4567],
"interval": 7
}
]}', true);
$results = array_filter($arr['people'], function($people) {
for($i=0; $i<count($people['member']); $i++){
return $people['member'][$i] == 123;
}
});
echo json_encode($results);
The out come will be:
[{"id":"8080","content":"foo","member":[123,456],"interval":7}]
If you want to do it withouth 'array_filter' you can try this:
function search($arr, $id, $arrayValue)
{
$people = null;
foreach ($arr['people'] as $a)
{
if ($a['id'] == $id)
{
$people = $a;
}
}
$arrayWeAreLookingFor = null;
foreach ($people as $property => $value)
{
if (is_array($value))
{
foreach ($value as $v)
{
if ($v == $arrayValue)
{
$arrayWeAreLookingFor = $people[$property];
}
}
}
}
return $arrayWeAreLookingFor;
}
var_dump(search($arr, 8080, 123));

How to access array inside document using PHP [duplicate]

This question already has answers here:
Get data from JSON file with PHP [duplicate]
(3 answers)
Closed 6 years ago.
I want print specific vars from array inside a document.
JSON structure:
{
"return": {
"string": "2222",
"contacts": [
{
"contact": {
"id": "09890423890"
}
},
{
"contact": {
"id": "2423444"
}
},
{
"contact": {
"id": "24242423"
}
},
etc
]
}
}
I am trying to do this in PHP (and already decoded that json). How can I access and print all ids using foreach or for?
I can not understand how I can manage "return" scope.
You can decode the json contents and use it like an array. This should work:
$json = json_decode($string, true);
$contacts = $json['return']['contacts'];
foreach($contacts as $contact){
echo $contact['contact']['id'];
}
Json decode to array:
$json = json_decode($strjson, true); // decode the JSON into an associative array
and
echo "<pre>";
print_r($json);
And foreach:
foreach ($json as $key => $value) {
echo $key . " ". $value. "<br>";
}
Working example:
$json = '{
"return": {
"string": "2222",
"contacts": [
{
"contact": {
"id": "09890423890"
}
},
{
"contact": {
"id": "2423444"
}
},
{
"contact": {
"id": "24242423"
}
}
]
}
}';
$json = json_decode($json, true);
print_r($json);
foreach ($json['return']['contacts'] as $val) {
echo $val['contact']['id']."<br>";
}
Try this code:
$json ='
{
"return": {
"string": "2222",
"contacts": [
{
"contact": {
"id": "09890423890"
}
},
{
"contact": {
"id": "2423444"
}
},
{
"contact": {
"id": "24242423"
}
},
etc
]
}
}
';
$array = json_decode($json,TRUE);
foreach($array['return']['contacts'] as $value ){
echo $value['id'];
}
Use file_get_contents function if you want to pull data from file.

Select individual column json in php

{
"responseData": {
"results": [
{
"title": "sobig",
"titleNoFormatting": "test",
},
{
"title": "test 2 ",
"titleNoFormatting": "test 2sd",
},
{
"title": "asdasdasda",
"titleNoFormatting": "asdasdasd",
},
{
"title": "A Warming",
"titleNoFormatting": "A Warming",
}
.
.
.
.
{
"title": "last thing",
"titleNoFormatting": "sada",
}
],
I have json files like this.
for($i=$veri1; $i <= $veri2; $i++) {
$uri = "http://test.com/json/".$i."/0";
$json = json_decode(file_get_contents($uri));
if($json->data->price >= $nakit && $json->data->odds >= $oran)
{
I'm getting some data with this code correctly from another json file.
i want get data from first json code, if "title" == "sobig" . How can I do that.
$json->responseData->results->title == sobig is not working. How can I get data if title is sobig
$json= json_decode($response, true);
foreach ($json['responseData']['results'] as $key => $value) {
if ($value == 'sobig') {
// found it
}
}
Try this example to see if this may fix your issue.
<?php
$json = '{ "responseData": {
"result" : [
{ "title": "sobig" , "titleNo":"test"},
{ "title": "loco" , "titleNo":"test"},
{ "title": "tom" , "titleNo":"test"}
]
}}';
$jsonDecoded = json_decode($json);
foreach ($jsonDecoded->responseData->result as $key => $value) {
var_dump($value); echo '<br>';
if($value->title == 'sobig'){
echo "we did it!!";
echo "<br>";
}
}
?>
I place a couple of var dumps so you can see the stucture of your object and why you need to use the foreach

search for duplicate classid in json array

I'm trying to search for duplicate classids in a json array and for each duplicate found, echo the dulicate id... This is just an example of the json file.
I've tried a few things but failed - if I posted my code it wouldn't work with this sample code. It's a lot more complex as after I am check another json file for matching ids... and a bunch of other stuff.
Thanks in advance.
{
"response": {
"received": [
{
"items": [
{
"classid": "356464564",
},
{
"classid": "456456456",
},
{
"classid": "356464564",
},
{
"classid": "721248158",
}
]
,
"time_created": 1440782791,
},
{
"items": [
{
"classid": "845362344",
},
{
"classid": "2543634754",
},
{
"classid": "2543634754",
},
{
"classid": "5967856788",
}
]
,
"time_created": 1440456791,
}
}
}
This can do what you're looking for:
<?php
$array = json_decode('{
"response": {
"received": [
{
"items": [
{
"classid": "356464564"
},
{
"classid": "456456456"
},
{
"classid": "356464564"
},
{
"classid": "721248158"
}
]
,
"time_created": 1440782791
}
]
}
}', true);
$cleanArray = array();
foreach($array['response']['received'][0]['items'] as $classid)
{
if(in_array($classid['classid'], $cleanArray))
echo "Duplicate found: ".$classid['classid'].'<br>';
else
$cleanArray[] = $classid['classid'];
}
?>
Try this, it makes the array smaller as matches are found, thus making the algorithm more efficient.
$arr = json_decode($json , true);
$items_array = array_column($arr['response']['items'], 'classid');
foreach ($items_array as $k => $val) {
foreach ($items_array as $k2 => $val2) {
if ($k2 != $k) {
if ($val == $val2) {
unset($items_array[$k]);
if (isset($final[$val])) {
$final[$val]++;
} else {
$final[$val] = 1;
}
}
}
}
}
var_dump($final); //will show you your duplicates

Categories