How can I access my nested array key in codeignigter? - php

"data": [
{
"pid": "81",
"fname": "Parth",
"lname": "Tandel",
"pfname": "Parth",
"plname": "Tandel",
"userprofilephoto": "/Images/ProfilePictures/18/DSC_0164.JPG",
"parentprofilephoto": "/Images/ProfilePictures/18/DSC_0164.JPG",
"type": "ALBUM",
"likescount": "1",
"commentscount": "1",
"sharecount": "0",
"sharepid": null,
"uaid": "18",
"ownerid": "18",
"parentid": null,
"title": "newalbum2",
"description": "",
"sharedescription": null,
"imagepath": null,
"previewurl": null,
"previewtitle": null,
"previewshortdescription": null,
"previewimageurl": null,
"createdon": "2017-05-29 15:44:04",
"posttype": "5",
"comments": [
{
"pcid": "21",
"uaid": "31",
"comment": "this is dope",
"fname": "maulik",
"lname": "kanani",
"profPicturepath": "https://www.gravatar.com/avatar/003dbb32079ee5ff19ed75476f562bd1",
"createdon": "2017-06-15 23:50:36"
}
],
"albumimages": [
{
"imagepath": "/Images/18/Albums/newalbum2/Screenshot_from_2017-06-12_15-11-36.png"
},
{
"imagepath": "/Images/18/Albums/newalbum2/Screenshot_from_2017-06-12_15-11-361.png"
},
{
"imagepath": "/Images/18/Albums/newalbum2/Screenshot_from_2017-06-12_15-11-363.png"
},
{
"imagepath": "/Images/18/Albums/newalbum2/Screenshot_from_2017-06-12_15-11-364.png"
},
{
"imagepath": "/Images/18/Albums/newalbum2/Screenshot_from_2017-06-12_15-11-365.png"
}
]
}
My PHP code
<?php
for ($i=0; $i < sizeof($value->albumimages); $i++)
{
$x = count($value->albumimages);
switch($x)
{
break;
default:
if($i == 0 || $i == 1)
{
echo '<div class="col-sm-6 pads5 marb10"> <img class="full" src="'.getapiPath().$imgs->imagepath.'"> </div>';
}
break;
}
}
?>
I want albumimages->imagepath

I think what you are looking for is json_decode($data, true);
This makes the json data an array that you can use like var_dump($data["albumimages"])
Working example: https://3v4l.org/Q9lkW
And to loop through the links you can do foreach, https://3v4l.org/9rRSF

Use this code
$a = json_decode('YOUR JSON STRING',true);
foreach($a['data'][0] as $key => $value){
if($key == 'albumimages'){
for($i = 0; $i < count($value); $i++){
foreach($value[$i] as $k => $v){
echo "Key: ".$k." Value: ".$v."<br/>";
}
}
}
}
Output will be like this
Key: imagepath Value: /Images/18/Albums/newalbum2/Screenshot_from_2017-06-12_15-11-36.png
Key: imagepath Value: /Images/18/Albums/newalbum2/Screenshot_from_2017-06-12_15-11-361.png
Key: imagepath Value: /Images/18/Albums/newalbum2/Screenshot_from_2017-06-12_15-11-363.png
Key: imagepath Value: /Images/18/Albums/newalbum2/Screenshot_from_2017-06-12_15-11-364.png
Key: imagepath Value: /Images/18/Albums/newalbum2/Screenshot_from_2017-06-12_15-11-365.png

for ($i=0; $i < sizeof($value->albumimages); $i++) {
$x = count($value->albumimages);
switch($x) {
default:
if($i == 0 || $i == 1)
{
echo '<div class="col-sm-6 pads5 marb10"> <img class="full" src="'.getapiPath().$value->albumimages[$i]->imagepath.'"> </div>';
}
break;
}
}

The data is in json format so convert the data into php object by using 'json_encode()' function. This function converts the json data into php object the access the property by using php object operator.
$data = json_encode('your_json_string');
//and access like this
$data[0]->albumimages
You can use the foreach loop to access the 'imagepath' like this
//get the albumsimages
$albumimages = $data[0]->albumimages;
//then use foreach to access the imagepath like this
foreach($albumimages as $image) {
echo $image->imagepath ."\n";
}
Check out working example here
PHP sandbox

Related

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;
}

create tree view like json from existing combined array

I have one combined array of order and its items combined into one array but i am trying to create json structure like order then its items list like wise.
$combinedarray[]=array('orderid'=>1,'partycode'=>10,"item"=>'abc',"price"=>250);
$combinedarray[]=array('orderid'=>1,'partycode'=>10,"item"=>'xyz',"price"=>250);
$combinedarray[]=array('orderid'=>2,'partycode'=>20,"item"=>'pqr',"price"=>250);
$combinedarray[]=array('orderid'=>2,'partycode'=>20,"item"=>'lmn',"price"=>250);
Output should be like
[
"0":[
{
"OrderNo": "1",
"partycode": "10",
"OrderDetails": [
{
"Item": "abc",
"price": 250
},
{
"Item": "xyz",
"price": 250
}
]
}
],
"1":[
{
"OrderNo": "2",
"partycode": "20",
"OrderDetails": [
{
"Item": "pqr",
"price": 250
},
{
"Item": "lmn",
"price": 250
}
]
}
]
]
This is What i Tried
$mainarray = array();
$orderarray = array();
$orderitemarray = array();
if (count(combinedarray) > 0) {
foreach (combinedarray as $obj) {
$orderarray[] = array("orderid" => $obj->orderid);
$orderitemarray[] = array("Item" => $obj->Item, "price" => $obj->price);
}
}
$mainarray[] = array_unique($orderarray);
$mainarray['OrderDetails'] = $orderitemarray;
echo json_encode($mainarray);
$mainarray = array();
foreach ($combinedarray as $x) {
$id = $x['orderid'];
unset($x['orderid']);
if (! isset($mainarray[$id])) {
$mainarray[$id]['OrderNo'] = $id;
}
$mainarray[$id]["OrderDetails"][] = $x;
}
// Now $mainarray has indexes equal to OrderNo. To count it from zero, use array_values
echo json_encode(array_values($mainarray), JSON_PRETTY_PRINT);
demo
By your given array
$combinedarray[]=array('orderid'=>1,'partycode'=>10,"item"=>'abc',"price"=>250);
$combinedarray[]=array('orderid'=>1,'partycode'=>10,"item"=>'xyz',"price"=>250);
$combinedarray[]=array('orderid'=>2,'partycode'=>20,"item"=>'pqr',"price"=>250);
$combinedarray[]=array('orderid'=>2,'partycode'=>20,"item"=>'lmn',"price"=>250);
Here is my solution for this
$new = array();
foreach($combinedarray as $r){
$new[$r['orderid']]['orderid'] = $r['orderid'];
$new[$r['orderid']]['partycode'] = $r['partycode'];
$new[$r['orderid']][] = array("item"=>$r['item'],"price"=>$r['price']);
}
$json = json_encode($new);
echo '<pre>';print_r($new);
echo $json;

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;
}
}
}

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

Getting JSON data from website returns " string(0) "

I;m trying to get data from a website using the following code:
<?php
$url = 'http://services.runescape.com/m=itemdb_oldschool/api/catalogue/detail.json?item=4798';
$content = file_get_contents($url);
var_dump($content);
$json = json_decode($content, true);
var_dump($json);
for ($idx = 0; $idx < count($json); $idx++) {
$obj = (Array)$json[$idx];
echo 'result' . $obj["name"];
}
?>
Which is getting me this result:
string(0) "" NULL
<?php
$url = 'http://services.runescape.com/m=itemdb_oldschool/api/catalogue/detail.json?item=4798';
$content = file_get_contents($url);
echo "<pre>";
//print_r($content);
$data = json_decode($content);
print_r($data); //Show the json decoded data comes form $url
##Parse this array {$data} using foreach loop as your use
?>
There are no numeric keys in the json returned from the url you posted in your question. So iterating through the associative array with numeric keys returns nothing.
This is the structure of the json you are working with:
{
"item": {
"icon": "http://services.runescape.com/m=itemdb_oldschool/5122_obj_sprite.gif?id=4798",
"icon_large": "http://services.runescape.com/m=itemdb_oldschool/5122_obj_big.gif?id=4798",
"id": 4798,
"type": "Default",
"typeIcon": "http://www.runescape.com/img/categories/Default",
"name": "Adamant brutal",
"description": "Blunt adamantite arrow... ouch.",
"current": {
"trend": "neutral",
"price": 529
},
"today": {
"trend": "neutral",
"price": 0
},
"members": "true",
"day30": {
"trend": "negative",
"change": "-9.0%"
},
"day90": {
"trend": "negative",
"change": "-20.0%"
},
"day180": {
"trend": "negative",
"change": "-31.0%"
}
}
}
Try accessing $json["item"]. That should give you something more meaningful to work with. If you want to iterate over the key/value pairs in the item, use a foreach loop:
foreach($json["item"] as $key => $value) {
echo $key . ":";
print_r($value);
}

Categories