Access variable Array Data PHP - 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;
}
}
}

Related

How to create a JSON with PHP?

I'm looking to order data from a Json file with PHP :
$url = 'data.json';
$json_string = file_get_contents($url);
$json = json_decode($json_string);
$rows = $json->values;
foreach($rows as $row) {
$jsonf .= json_encode(array(
"$row[0]" => array(
"name" => "$row[1]",
"value" => "$row[2]",
"conso" => "$row[3]",
"ml" => "$row[4]"
)
), JSON_UNESCAPED_UNICODE);
}
Unfortunately, with this method, I get a bad result:
{
"DATA_01": {
"name": "name_01",
"value": "value_01",
"conso": "conso_01",
"ml": "ml_01"
}
} {
"DATA_02": {
"name": "name_02",
"value": "value_02",
"conso": "conso_02",
"ml": "ml_02"
}
} {
"DATA_03": {
"name": "name_03",
"value": "value_03",
"conso": "conso_03",
"ml": "ml_03"
}
}
I would rather get something like this:
{
"DATA_01": {
"name": "name_01",
"value": "value_01",
"conso": "conso_01",
"ml": "ml_01"
},
"DATA_02": {
"name": "name_02",
"value": "value_02",
"conso": "conso_02",
"ml": "ml_02"
},
"DATA_03": {
"name": "name_03",
"value": "value_03",
"conso": "conso_03",
"ml": "ml_03"
}
}
Could someone help me solve my problem.
Thank you very much for all the help you can give me.
I am not really sure what you want to accomplish, but I think it is the following:
You get this result because you are putting the json_encode function within a for-loop. put all your detain an array, and encode it after that. Your code will become like this:
foreach($rows as $row) {
$data[] = $row[0];
}
json_encode($data)

Clean Up GraphQL Response and Convert to JSON without edges and nodes

I am calling the Shopify admin api.
When I use the REST API, I get beautiful JSON objects in my responses.
[{
{
"id": 7036594978985,
"title": "7 Shakra Bracelet",
"body_html": "<p>7 chakra bracelet, in blue or black.</p>",
"vendor": "Company 123",
"product_type": "Bracelet",
"created_at": "2021-06-17T17:45:05-04:00",
"handle": "chain-bracelet",
"updated_at": "2021-06-23T20:08:21-04:00",
"published_at": "2021-06-17T17:45:04-04:00",
"template_suffix": null,
"published_scope": "web",
"tags": "Beads, Bracelet",
"admin_graphql_api_id": "gid://shopify/Product/7036594978985",
"variants": [
{
"id": 40671266963625,
"product_id": 7036594978985,
"title": "Blue",
"price": "42.99",
"sku": null,
"position": 1,
"inventory_policy": "deny",
"compare_at_price": "44.99",
"fulfillment_service": "manual",
"inventory_management": null,
"option1": "Blue",
}
},
{
id: 7036594978986
...
]
However, if I use GraphQL I end up with a bunch of edges and nodes that don't play well with my front end JS.
{
"products": {
"edges": [
{
"node": {
"description": "Sleek and black",
"featuredImage": {
"id": "gid://shopify/ProductImage/15464783282345",
"originalSrc": "https://cdn.shopify.com/s/files/1/0268/1005/6873/products/bb20.jpg?v=1602116082"
},
"handle": "skirt",
"id": "gid://shopify/Product/4773734482089",
"images": {
"edges": [
{
"node": {
"id": "gid://shopify/ProductImage/15464783282345",
"originalSrc": "https://cdn.shopify.com/s/files/1/0268/1005/6873/products/bb20.jpg?v=1602116082"
}
},
{
"node": {
"id": "gid://shopify/ProductImage/26072838406313",
"originalSrc": "https://cdn.shopify.com/s/files/1/0268/1005/6873/products/bb7.jpg?v=1612636091"
}
},
{
"node": {
"id": "gid://shopify/ProductImage/26072838373545",
"originalSrc": "https://cdn.shopify.com/s/files/1/0268/1005/6873/products/bb6.jpg?v=1612636091"
}
}
]
},
I'd like to flatten the array a little bit by replacing all edges and nodes with the friendly minimal JSON structure.
From this:
{
"products": {
"edges": [
{
"node": {
"description": "Sleek and black",
"featuredImage": {
"id": "gid://shopify/ProductImage/15464783282345",
"originalSrc": "https://cdn.shopify.com/s/files/1/0268/1005/6873/products/bb20.jpg?v=1602116082"
},
To this:
{
"products": [
{
"description": "Sleek and black",
"featuredImage": {
"id": "gid://shopify/ProductImage/15464783282345",
"originalSrc": "https://cdn.shopify.com/s/files/1/0268/1005/6873/products/bb20.jpg?v=1602116082"
},
I'd like to be able to call a recursive PHP function to replace all nodes and edges nested in the array.
I tried this, but I think it causes iteration issues.
public function parse_and_remove (&$arr) {
foreach ($arr as $key => $val) {
if (($key == 'edges' || $key == 'node') && (is_array($val) || is_object($val))) {
$arr = $val;
$val = $this->parse_and_remove($val);
} else if (is_array($val) || is_object($val)) {
$val = $this->parse_and_remove($val);
} else {
}
}
return $arr;
}
PART II
How is everyone okay with this kind of response in GraphQL? It's a pain to work with on the front end where API responses are often consumed. Don't give me the array of edges and the node then finally the object. I just want that array of objects :)
I finally created a function that did it. It is terribly inefficient because every time I move a node up to replace the parent, I break and restart the entire loop in order to be able to parse the parent again.
$nice_data = $this->move_value_at_node_to_parent($response['body']['data'], 'node');
$nice_data2 = $this->move_value_at_node_to_parent($nice_data, 'edges');
the function: (no indentation because I like prefer the ease of repetition with code alignment - * the foreach loops are nested)
public function move_value_at_node_to_parent($obj, $key_name) {
// make array
$obj_string = json_encode($obj);
$arr = json_decode($obj_string, true);
// do this a bunch to avoid index problems
for ($i=0; $i < 1000; $i++) {
if(!is_array($arr)) continue;
foreach ($arr as $key => $val) {
if($key == $key_name) {
$arr = $val;
break;
}
$arr2 = $arr[$key];
if(!is_array($arr2)) continue;
foreach ($arr2 as $key2 => $val2) {
if($key2 == $key_name) {
$arr[$key] = $val2;
break;
}
$arr3 = $arr[$key][$key2];
if(!is_array($arr3)) continue;
foreach ($arr3 as $key3 => $val3) {
if($key3 == $key_name) {
$arr[$key][$key2] = $val3;
break;
}
$arr4 = $arr[$key][$key2][$key3];
if(!is_array($arr4)) continue;
foreach ($arr4 as $key4 => $val4) {
if($key4 == $key_name) {
$arr[$key][$key2][$key3] = $val4;
break;
}
$arr5 = $arr[$key][$key2][$key3][$key4];
if(!is_array($arr5)) continue;
foreach ($arr5 as $key5 => $val5) {
if($key5 == $key_name) {
$arr[$key][$key2][$key3][$key4] = $val5;
break;
}
$arr6 = $arr[$key][$key2][$key3][$key4][$key5];
if(!is_array($arr6)) continue;
foreach ($arr6 as $key6 => $val6) {
if($key6 == $key_name) {
$arr[$key][$key2][$key3][$key4][$key5] = $val6;
break;
}
$arr7 = $arr[$key][$key2][$key3][$key4][$key5][$key6];
if(!is_array($arr7)) continue;
foreach ($arr7 as $key7 => $val7) {
if($key7 == $key_name) {
$arr[$key][$key2][$key3][$key4][$key5][$key6] = $val7;
break;
}
}
}
}
}
}
}
}
}
return $arr;
}

How to display info on double array JSON (php)

I would like to know how to display the information below.
Link (JSON):
https://my.callofduty.com/api/papi-client/ce/v1/title/bo4/platform/psn/match/11337378706913618925/matchMapEvents
What I wish to have:
"teams": [
[
{
"provider": "psn",
"username": "Germania1992"
},
{
"provider": "psn",
"username": "killzoneprofi"
},
{
"provider": "psn",
"username": "ayozetf87"
},
{
"provider": "psn",
"username": "Seith911"
},
{
"provider": "psn",
"username": "domibreu92"
}
],
[
{
"provider": "psn",
"username": "Thejuankarboy"
},
{
"provider": "psn",
"username": "Gamermad101"
},
{
"provider": "psn",
"username": "Izdrap"
},
{
"provider": "psn",
"username": "Guerra_sv"
},
{
"provider": "psn",
"username": "TriX_FollOoW_YT"
}
]
],
I want to display the nicks of the different teams
Example: Team 1 = Germania1992, killzoneprofi, ayozetf87, Seith911,
domibreu92
Thanks
You will have to do a double foreach that for sure.
<?php
// Get the json of the team
$team = team("https://my.callofduty.com/api/papi-client/ce/v1/title/bo4/platform/psn/match/11337378706913618925/matchMapEvents");
// Display the teams info
foreach($team as $nb=>$data){
echo "Team $nb<br />";
foreach($data as $key=>$value){
echo "Provider: ".$value->provider."<br />";
echo "Username: ".$value->username."<br />";
}
echo "<hr>";
}
// Returns the team array of the json
function team($jsonURL){
$content=file_get_contents($jsonURL);
$data=json_decode($content);
return $data->data->teams;
}
?>
You could increment the team number by 1 to avoid the first being 0
The above will display the below screenshot (You can format the output as you please)
$result = [];
$counter = 0;
dump($array = json_decode(file_get_contents('https://my.callofduty.com/api/papi-client/ce/v1/title/bo4/platform/psn/match/11337378706913618925/matchMapEvents')));
dump($t = array_column((array)$array, 'teams'));
foreach ($t as $r) {
foreach ($r as $p) {
$counter++;
foreach ($p as $value){
$result["team$counter"][] = $value->username;
}
}
}
var_dump($result);

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

How to place the json objects into array usin php?

this is my php code, to obtain json format data
if($status==1)
{
$post_id=$json_object['post_id'];
$get_postid=mysqli_query($con,"select * from User_Post where post_id='$post_id'");
if(mysqli_num_rows($get_postid)==0)
{
//For failure status if session id is wrong.
http_response_code(500);
echo json_encode(array("error_code"=>"500","error_message"=>"Sorry, post id does not exists."));
}
else
{
foreach($field_check as $values)
{
if($values=='id')
{
$row_array = array();
while ($row = $get_postid->fetch_array())
{
$row_array['id']=$row['post_id'];
$row_array['image_urls']=explode(',',$row['post_image_url']);
$storetag= explode(',',$row['Post_tagged_id']);
$has_liked="false";
$has_commented="false";
}
}
elseif($values=='tagged_users')
{
while ($row = $get_postid->fetch_array())
{
$storetag= explode(',',$row['Post_tagged_id']);
$has_liked="false";
$has_commented="false";
}
for($i=0;$i<count($storetag);$i++)
{
$user=mysqli_query($con,"select user_id, profile_image_url from Wheel_User where user_id='$storetag[$i]'");
if(mysqli_num_rows($user)==0)
{
//For failure status if session id is wrong.
http_response_code(500);
echo json_encode(array("error_code"=>"500","error_message"=>"Sorry, post id does not exists.".die()));
}
else
{
while ($row = $user->fetch_array())
{
$tagged_users[$i]['user_id']=$row['user_id'];
$array['user_id']=$tagged_users[$i]['user_id'];
$pro_image_url[$i]=$row['profile_image_url'];
$short_image_url[$i]=str_replace('_b','_t',$pro_image_url[$i]);
$short_image_url[$i]=str_replace('/images/','/thumbnails/',$short_image_url[$i]);
$array['short_image_url']=$short_image_url[$i];
}
}
array_push($row_array,$array);
}
}
}
array_push($json_response,$row_array);
echo str_replace('\/','/',json_encode($json_response));
}
}
It is returning the following objects
[
{
"id": "1111",
"image_urls": [
"https://docs.google.com/document/d/14kVqw9d2kzYIEClN-SVp2Co2mlglM9F-8HIy0ggTZ3g/edit",
"http://stackoverflow.com/questions/21762150/how-do-i-insert-data-from-a-json-array-into-mysql-database",
"https://drive.google.com/?authuser=0#my-drive",
"https://drive.google.com/?tab=mo&authuser=0#shared-with-me"
],
"0": {
"user_id": "111",
"short_image_url": "chrome://restclient/content/thumbnails/restclient_t.jpg"
},
"1": {
"user_id": "321",
"short_image_url": "chrome://restclient/thumbnails/restclient_t.jpg"
},
"2": {
"user_id": "1234",
"short_image_url": "http://54.169.40.195/wheel/wheel/service/testing/chetan/audio/c71dfe45421b2864476a0bde257f0a57e72084783ce859e26595599670904907.mp3"
}
}
]
but i want to assign name to that array like this
[
{
"id": "1111",
"image_urls": [
"https://docs.google.com/document/d/14kVqw9d2kzYIEClN-SVp2Co2mlglM9F-8HIy0ggTZ3g/edit",
"http://stackoverflow.com/questions/21762150/how-do-i-insert-data-from-a-json-array-into-mysql-database",
"https://drive.google.com/?authuser=0#my-drive",
"https://drive.google.com/?tab=mo&authuser=0#shared-with-me"
],
"tagged_users":[
"0": {
"user_id": "111",
"short_image_url": "chrome://restclient/content/thumbnails/restclient_t.jpg"
},
"1": {
"user_id": "321",
"short_image_url": "chrome://restclient/thumbnails/restclient_t.jpg"
},
"2": {
"user_id": "1234",
"short_image_url": "http://54.169.40.195/wheel/wheel/service/testing/chetan/audio/c71dfe45421b2864476a0bde257f0a57e72084783ce859e26595599670904907.mp3"
}
]
}
i don't know where i have to add this array name. Please help me solve this.
I can't assign the array name like this because $row_array also contains other data
echo str_replace('\/','/',json_encode(array("tagged_user"=>$json_response));
On second to last line this should be what you wanted:
array_push($json_response,array("tagged_users" => $row_array));
Edited to remove second part.
Try with -
array_push($row_array['tagged_users'],$array);
Or define it like -
$row_array['tagged_users'] = array();
Then all the values will be as you want.

Categories