i am trying to get Youtube channel data with that api
https://www.googleapis.com/youtube/v3/channels?part=snippet,contentDetails,statistics&id={ Channel Id }&key={ API }
I used that code to fetch the data
if( $_SERVER[ 'REQUEST_METHOD' ] == 'GET' && !empty( $_GET ) ){
$channel_id = $_GET[ 'channel_id' ];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://www.googleapis.com/youtube/v3/channels?part=snippet,contentDetails,statistics&id=". $channel_id ."&key=AIzaSyCKAnI41bI4UGDJgYUcwrhrIfnjoD3uirM",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_POSTFIELDS => "",
CURLOPT_HTTPHEADER => array(
"content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
}
?>
<form id="channelIdForm" action="<?php $_SERVER['PHP_SELF']; ?>" method="get">
<input type="text" placeholder="Type channel id" name="channel_id" id="channelId" />
<button type="submit">Get data</button>
</form>
And it appeared like that
{ "kind": "youtube#channelListResponse", "etag": "\"DuHzAJ-eQIiCIp7p4ldoVcVAOeY/pss5QFB6saoevVwzX-8y6f1U75E\"", "pageInfo": { "totalResults": 1, "resultsPerPage": 1 }, "items": [ { "kind": "youtube#channel", "etag": "\"DuHzAJ-eQIiCIp7p4ldoVcVAOeY/gPFze0Hh7eRu9O5tXiTBVyvCwa8\"", "id": "UC4QYTjhWMxiC6UwvKLVkDDA", "snippet": { "title": "حفيد برايز حفيد برايز", "description": "", "publishedAt": "2018-04-01T17:18:31.000Z", "thumbnails": { "default": { "url": "https://yt3.ggpht.com/-wuTRH4WK_UA/AAAAAAAAAAI/AAAAAAAAAAA/ms_Qpu4ekLk/s88-c-k-no-mo-rj-c0xffffff/photo.jpg", "width": 88, "height": 88 }, "medium": { "url": "https://yt3.ggpht.com/-wuTRH4WK_UA/AAAAAAAAAAI/AAAAAAAAAAA/ms_Qpu4ekLk/s240-c-k-no-mo-rj-c0xffffff/photo.jpg", "width": 240, "height": 240 }, "high": { "url": "https://yt3.ggpht.com/-wuTRH4WK_UA/AAAAAAAAAAI/AAAAAAAAAAA/ms_Qpu4ekLk/s800-c-k-no-mo-rj-c0xffffff/photo.jpg", "width": 800, "height": 800 } }, "localized": { "title": "حفيد برايز حفيد برايز", "description": "" } }, "contentDetails": { "relatedPlaylists": { "uploads": "UU4QYTjhWMxiC6UwvKLVkDDA", "watchHistory": "HL", "watchLater": "WL" } }, "statistics": { "viewCount": "830460", "commentCount": "0", "subscriberCount": "3741", "hiddenSubscriberCount": false, "videoCount": "19" } } ] }
Then i tried to convert that json to an array to pick what i want from it with index
So i tried that instead of $response
$json = $response;
$arr = json_decode($json, true);
$row = array_reduce($arr['items'], function($c, $v){
$c[ key($v) ] = current($v);
return $c;
}, array());
print_r( $row );
I expected to see all the indexes below item but the result was
Array ( [kind] => youtube#channel )
It show just kind i don't know what the problem with so if any one can help i will be appreciated!!
The array_reduce function reduces an array to a single value. But it appears you are interested in multiple key/value pairs. Since json_decode($json, true); already provides you with an associated array you can retrieve specific keys via their names. Example:
$arr = json_decode($response, true);
$newArray = [];
$requiredKeys = ['kind','etag'];
foreach ($requiredKeys as $key){
$newArray[$key] = $arr[$key];
}
It is a very-multi-dimensional array.
Here's some code that prints the contents of an array. If the value it is going to print is an array, it calls itself again. You'll see it puts out Printing $json_arr[items[0][statistics] : followed by a bunch of key->value pairs, so you can find the state you want and you'll know what the parent array(s) are.
<?php
$json='{ "kind": "youtube#channelListResponse", "etag": "\"DuHzAJ-eQIiCIp7p4ldoVcVAOeY/pss5QFB6saoevVwzX-8y6f1U75E\"", "pageInfo": { "totalResults": 1, "resultsPerPage": 1 }, "items": [ { "kind": "youtube#channel", "etag": "\"DuHzAJ-eQIiCIp7p4ldoVcVAOeY/gPFze0Hh7eRu9O5tXiTBVyvCwa8\"", "id": "UC4QYTjhWMxiC6UwvKLVkDDA", "snippet": { "title": "حفيد برايز حفيد برايز", "description": "", "publishedAt": "2018-04-01T17:18:31.000Z", "thumbnails": { "default": { "url": "https://yt3.ggpht.com/-wuTRH4WK_UA/AAAAAAAAAAI/AAAAAAAAAAA/ms_Qpu4ekLk/s88-c-k-no-mo-rj-c0xffffff/photo.jpg", "width": 88, "height": 88 }, "medium": { "url": "https://yt3.ggpht.com/-wuTRH4WK_UA/AAAAAAAAAAI/AAAAAAAAAAA/ms_Qpu4ekLk/s240-c-k-no-mo-rj-c0xffffff/photo.jpg", "width": 240, "height": 240 }, "high": { "url": "https://yt3.ggpht.com/-wuTRH4WK_UA/AAAAAAAAAAI/AAAAAAAAAAA/ms_Qpu4ekLk/s800-c-k-no-mo-rj-c0xffffff/photo.jpg", "width": 800, "height": 800 } }, "localized": { "title": "حفيد برايز حفيد برايز", "description": "" } }, "contentDetails": { "relatedPlaylists": { "uploads": "UU4QYTjhWMxiC6UwvKLVkDDA", "watchHistory": "HL", "watchLater": "WL" } }, "statistics": { "viewCount": "830460", "commentCount": "0", "subscriberCount": "3741", "hiddenSubscriberCount": false, "videoCount": "19" } } ] } ';
$json_arr=json_decode($json,true);
function print_array($prefix,$arr){
print("printing ".$prefix." :\n");
foreach($arr as $k=>$v){
if(is_array($v)){
print_array($prefix."[".$k."]",$v);
}else{
print("key: ".$k." value:".$v." \n");
}
}
return;
}
print_array("\$json_arr",$json_arr);
?>
Related
Hello I found a problem displaying url value.
Is the problem in " Array ( " ?
Array ( [ {
"playabilityStatus": {
"status": "OK", "playableInEmbed": true, "contextParams": "Q0FFU0FnZ0M] => "
}
, "streamingData": {
"expiresInSeconds":"21540", "formats":[ {
"itag": 18, "url": "http://example.com/360.mp4", "mimeType": "video/mp4; codecs=\"avc1.42001E, mp4a.40.2\"", "bitrate": 198298, "width": 638, "height": 360, "lastModified": "1567026236090610", "contentLength": "20775840", "quality": "medium", "qualityLabel": "360p", "projectionType": "RECTANGULAR", "averageBitrate": 198286, "audioQuality": "AUDIO_QUALITY_LOW", "approxDurationMs": "838217", "audioSampleRate": "44100", "audioChannels": 1
}
, {
"itag": 22, "url": "http://example.com/360x1.mp4", "mimeType": "video/mp4; codecs=\"avc1.64001F, mp4a.40.2\"", "bitrate": 404000, "width": 1276, "height": 720, "lastModified": "1567026270240429", "quality": "hd720", "qualityLabel": "720p", "projectionType": "RECTANGULAR", "audioQuality": "AUDIO_QUALITY_MEDIUM", "approxDurationMs": "838217", "audioSampleRate": "44100", "audioChannels": 1
}
, {
"itag": 43, "url": "http://example.com/360x2.mp4", "mimeType": "video/webm; codecs=\"vp8.0, vorbis\"", "bitrate": 2147483647, "width": 640, "height": 360, "lastModified": "1567026831970178", "contentLength": "19705302", "quality": "medium", "qualityLabel": "360p", "projectionType": "RECTANGULAR", "audioQuality": "AUDIO_QUALITY_MEDIUM"
}
], "adaptiveFormats":[
...
$arr is = php file ytb-dl.php
$json_output = json_decode($arr);
foreach ($json_output['streamingData'] as $formats) {
echo $formats['url'];
}
Be aware which structure of data you are using, try code below, is working for me.
Please check if link https://webstickers.000webhostapp.com/ytb-dl.php is active.
$content = file_get_contents('https://webstickers.000webhostapp.com/ytb-dl.php');
$json_output = json_decode($content, true);
foreach ($json_output['streamingData'] as $formats) {
if (!is_array($formats)) {
continue;
}
foreach ($formats as $format) {
echo $format['url'] . PHP_EOL;
}
}
I am accessing API for "ConnectWise". the data comes into JSON format. i was able to parse the data into table via PHP. however, empty fields in JSON results in Undefined index. This happens for some items with no website, or address for example. the rest shows up fine.
Any help or input would be appreciated.
Here is my code to get the data from Connectwise:
function get_companies(){
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($curl, CURLOPT_URL, "https://api-
na.myconnectwise.net/v4_6_release/apis/3.0/company/companies");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"Authorization: Basic (OUR KEY)",
'Content-type: application/json'
));
$result = curl_exec($curl);
curl_close($curl);
$decoded = json_decode($result,true);
return $decoded;
}
And to display the data:
function list_all_accounts(){
$accounts = get_companies();
if ( !empty ($accounts)){
foreach ($accounts as $account) {
{
echo "
</td>
<td>
$account[id]
</td>
<td>
$account[name]
</td>
<td>
$account[addressLine1]
</td>
<td>
$account[phoneNumber]
</td>
<td>
$account[website]
</td>
<td>
$account[name]
</td>
</tr>";
}
}
}
}
Update - Json Sample
[
{
"id": 250,
"identifier": "company name ",
"name": "company name",
"status": {
"id": 1,
"name": "Active",
"_info": {
"status_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies/statuses/1"
}
},
"type": {
"id": 1,
"name": "Client",
"_info": {
"type_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies/types/1"
}
},
"addressLine1": "address line 1",
"city": "New York",
"state": "NY",
"zip": "11111",
"country": {
"id": 1,
"name": "United States",
"_info": {
"country_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/countries/1"
}
},
"phoneNumber": "123456789",
"faxNumber": "",
"website": "www.site.com",
"territoryId": 2,
"accountNumber": "",
"dateAcquired": "2006-06-21T04:00:00Z",
"sicCode": {
"id": 1209,
"name": "consulting"
},
"annualRevenue": 0,
"timeZone": {
"id": 1,
"name": "GMT-5/Eastern Time: US & Canada",
"_info": {
"timeZoneSetup_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/system/timeZoneSetups/1"
}
},
"leadFlag": false,
"unsubscribeFlag": false,
"userDefinedField5": "1",
"taxCode": {
"id": 8,
"name": "Tax-State",
"_info": {
"taxCode_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/finance/taxCodes/8"
}
},
"billingTerms": {
"id": 1,
"name": "Net 30 days"
},
"billToCompany": {
"id": 250,
"identifier": "comp1 ",
"name": "company1.",
"_info": {
"company_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies/250"
}
},
"billingSite": {
"id": 1291,
"name": "company1",
"_info": {
"site_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies"
}
},
"invoiceDeliveryMethod": {
"id": 1,
"name": "Mail"
},
"deletedFlag": false,
"mobileGuid": "1df91371-6d7a-4778-ab81-f3e7761f5211",
"currency": {
"id": 7,
"symbol": "$",
"isoCode": "USD",
"name": "US Dollars",
"_info": {
"currency_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/finance/currencies/7"
}
},
"_info": {
"lastUpdated": "2018-04-02T16:36:05Z",
"updatedBy": "user1",
"dateEntered": "2006-06-21T16:04:59Z",
}
},
{
"id": 250,
"identifier": "company name ",
"name": "company name",
"status": {
"id": 1,
"name": "Active",
"_info": {
"status_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies/statuses/1"
}
},
"type": {
"id": 1,
"name": "Client",
"_info": {
"type_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies/types/1"
}
},
"addressLine1": "address line 1",
"city": "New York",
"state": "NY",
"zip": "11111",
"country": {
"id": 1,
"name": "United States",
"_info": {
"country_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/countries/1"
}
},
"phoneNumber": "123456789",
"faxNumber": "",
"website": "www.site.com",
"territoryId": 2,
"accountNumber": "",
"dateAcquired": "2006-06-21T04:00:00Z",
"sicCode": {
"id": 1209,
"name": "consulting"
},
"annualRevenue": 0,
"timeZone": {
"id": 1,
"name": "GMT-5/Eastern Time: US & Canada",
"_info": {
"timeZoneSetup_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/system/timeZoneSetups/1"
}
},
"leadFlag": false,
"unsubscribeFlag": false,
"userDefinedField5": "1",
"taxCode": {
"id": 8,
"name": "Tax-State",
"_info": {
"taxCode_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/finance/taxCodes/8"
}
},
"billingTerms": {
"id": 1,
"name": "Net 30 days"
},
"billToCompany": {
"id": 250,
"identifier": "comp1 ",
"name": "company1.",
"_info": {
"company_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies/250"
}
},
"billingSite": {
"id": 1291,
"name": "company1",
"_info": {
"site_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies"
}
},
"invoiceDeliveryMethod": {
"id": 1,
"name": "Mail"
},
"deletedFlag": false,
"mobileGuid": "1df91dd371-6d7addd-4778s-ab81-f3e7761f5211",
"currency": {
"id": 7,
"symbol": "$",
"isoCode": "USD",
"name": "US Dollars",
"_info": {
"currency_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/finance/currencies/7"
}
},
"_info": {
"lastUpdated": "2018-04-02T16:36:05Z",
"updatedBy": "user1",
"dateEntered": "2006-06-21T16:04:59Z",
"enteredBy": "CONVERSION",
}
}
]
json_decode() and https://jsonlint.com/ both complain about the comma after the value on lines 95 and 194. Removing them makes it valid json, after which your code works as soon as you remember to quote the key values for the associative array.
I removed the two offending commas in the json and saved as a file, then added the quoting for your key values on the array, and finally removed the HTML table stuff and such (I'm just running it on command line to see output). Should be easy to put back in...
<?php
function get_companies() {
$j = file_get_contents("json.json");
$jd = json_decode($j, true);
return $jd;
}
$accounts = get_companies();
if (!empty($accounts)) {
foreach ($accounts as $account) {
echo "\n".$account['id'] . "
" . $account['name'] . "
" . $account['addressLine1'] . "
" . $account['phoneNumber'] . "
" . $account['website'] . "
" . $account['name']."\n\n";
}
}
?>
According to your comment, it is possible that some properties that you use in your HTML are not part of the JSON you receive. This means you are accessing an array index that is not set, e.g. with $account[website].
I see two solutions for this:
Only output the data if it is set in the array:
echo '<td>'.(isset($account['website']) ? $account['website'] : '').'</td>';
Use a an array with defaults for all the values as base for your $account array and merge them:
$base = [
'website' => 'no website',
'phoneNumber' => '',
];
foreach ($accounts as $account) {
// this will override all elements of $base with them of $account,
// but only if they are present in $account
$account = array_merge($base, $account);
// ... your output here ...
}
I have this array of object:
[
{
"id": 1,
"name": "Carbo",
"menus": [
{
"id": 33,
"name": "FloralWhite",
"image": {
"web": "https://lorempixel.com/640/360/food/?89722",
"mobile": "https://lorempixel.com/640/360/food/?89722",
"square": "https://lorempixel.com/640/360/food/?89722"
},
"logs": {
"price": 2
}
},
{
"id": 40,
"name": "LightGray",
"image": {
"web": "https://lorempixel.com/640/360/food/?63930",
"mobile": "https://lorempixel.com/640/360/food/?63930",
"square": "https://lorempixel.com/640/360/food/?63930"
},
"logs": {
"price": 2
}
},
]
}
]
What I want to achieve:
[
{
"id": 1,
"name": "Carbo",
"menus": [
{
"id": 33,
"name": "FloralWhite",
"image": {
"web": "https://lorempixel.com/640/360/food/?89722",
"mobile": "https://lorempixel.com/640/360/food/?89722",
"square": "https://lorempixel.com/640/360/food/?89722"
},
"price": 2
},
{
"id": 40,
"name": "LightGray",
"image": {
"web": "https://lorempixel.com/640/360/food/?63930",
"mobile": "https://lorempixel.com/640/360/food/?63930",
"square": "https://lorempixel.com/640/360/food/?63930"
},
"price": 2
},
]
}
]
I've tried using laravel collection flatten with depth but it fail
$data = collect($data->menus);
$data = $data->flatten(1);
$data->values()->all();
How can I flatten the menus['logs'] object so it can one level with menu?
Something like this should do the trick. Simply iterate over your array, set the new property and remove the one you don't want.
$data = json_decode("[{
\"id\": 1,
\"name\": \"Carbo\",
\"menus\": [
{
\"id\": 33,
\"name\": \"FloralWhite\",
\"image\": {
\"web\": \"https://lorempixel.com/640/360/food/?89722\",
\"mobile\": \"https://lorempixel.com/640/360/food/?89722\",
\"square\": \"https://lorempixel.com/640/360/food/?89722\"
},
\"logs\": {
\"price\": 2
}
},
{
\"id\": 40,
\"name\": \"LightGray\",
\"image\": {
\"web\": \"https://lorempixel.com/640/360/food/?63930\",
\"mobile\": \"https://lorempixel.com/640/360/food/?63930\",
\"square\": \"https://lorempixel.com/640/360/food/?63930\"
},
\"logs\": {
\"price\": 2
}
}
]
}]");
foreach($data as $val){
foreach($val->menus as $menuVal){
$menuVal->price = $menuVal->logs->price;
unset($menuVal->logs);
}
}
#Stefen Suhat i really don't know what is the syntax for laravel but i did it with a simple php foreach() hope this will help you, as your array's depth is long so i had gone to all the levels of your array, check code and output snippet here https://eval.in/806879
try below one:
<?php
$array = array(
array(
"id"=> 1,
"name"=> "Carbo",
"menus"=> array(
array(
"id"=> 33,
"name"=> "FloralWhite",
"image"=> array(
"web"=> "https=>//lorempixel.com/640/360/food/?89722",
"mobile"=> "https=>//lorempixel.com/640/360/food/?89722",
"square"=> "https=>//lorempixel.com/640/360/food/?89722"
),
"logs"=> array(
"price"=> 2
)
),
array(
"id"=> 40,
"name"=> "LightGray",
"image"=> array(
"web"=> "https=>//lorempixel.com/640/360/food/?63930",
"mobile"=> "https=>//lorempixel.com/640/360/food/?63930",
"square"=> "https=>//lorempixel.com/640/360/food/?63930"
),
"logs"=> array(
"price"=> 2
)
),
)
)
);
foreach($array as $key => $value){
foreach ($value as $key1 => $value1) {
if(is_array($value1) && $key1 == "menus"){
foreach($value1 as $key2 => $value2) {
foreach ($value2 as $key3 => $value3) {
if(is_array($value3) && $key3 == "logs"){
unset($array[$key][$key1][$key2][$key3]);
$array[$key][$key1][$key2] = array_merge($array[$key][$key1][$key2], $value3);
}
}
}
}
}
}
echo "array after<br>";
echo "<pre>";
print_r($array); //your array after
?>
I am trying to get data from a multidimensional array I got from a Facebook response, into a simpler array.
the json data is as seen below.
{
"albums": {
"data": [
{
"photos": {
"data": [
{
"name": "a photo name",
"source": "https://fbcdn-sphotos-d-a.akamaihd.net/hphotos-ak-xlp1/t31.0-8/s720x720/XXXXXXXXXXXX",
"picture": "https://fbcdn-photos-d-a.akamaihd.net/hphotos-ak-xfp1/v/t1.0-0/XXXXXXXXXXXXXX",
},
{
"name": "a photo name",
"source": "https://fbcdn-photos-d-a.akamaihd.net/hphotos-ak-xtp1/v/t1.0-0/p480x480/XXXXXXXXXXXXXXXXXX",
"picture": "https://fbcdn-photos-d-a.akamaihd.net/hphotos-ak-xtp1/v/t1.0-0/s130x130/XXXXXXXXXXXX",
},
{
"name": "a photo name",
"source": "https://fbcdn-photos-d-a.akamaihd.net/hphotos-ak-xtf1/v/t1.0-0/p480x480/XXXXXXXXXXXXXX",
"picture": "https://fbcdn-photos-d-a.akamaihd.net/hphotos-ak-xtf1/v/t1.0-0/s130x130/XXXXXXXXXXXXXXX",
},
{
"name": "a photo name",
"source": "https://fbcdn-photos-b-a.akamaihd.net/hphotos-ak-xap1/v/t1.0-0/p480x480/XXXXXXXXXXXXXXXXXX",
"picture": "https://fbcdn-photos-b-a.akamaihd.net/hphotos-ak-xap1/v/t1.0-0/s130x130/XXXXXXXXXXXX",
}
],
"paging": {
"cursors": {
"before": "MTXXXXXXXXXXXXXXXZD",
"after": "MXXXXXXXXXXXXXZD"
}
}
},
},
{
"photos": {
"data": [
{
"source": "https://fbcdn-sphotos-f-a.akamaihd.net/hphotos-ak-xfp1/v/t1.0-9/XXXXXXXXXXXXXXX",
"picture": "https://fbcdn-photos-b-a.akamaihd.net/hphotos-ak-xfp1/v/t1.0-0/s130x130/XXXXXXXXXXXX",
},
{
"name": "XXXXXXXXX",
"source": "https://fbcdn-sphotos-e-a.akamaihd.net/hphotos-ak-xpa1/v/t1.0-9/XXXXXXXXXXX",
"picture": "https://fbcdn-photos-a-a.akamaihd.net/hphotos-ak-xpa1/v/t1.0-0/s130x130/XXXXXXXXXXXX",
},
{
"name": "XXXXXXXXXXX",
"source": "https://fbcdn-sphotos-c-a.akamaihd.net/hphotos-ak-xap1/v/t1.0-9/XXXXXXXXXXX",
"picture": "https://fbcdn-photos-c-a.akamaihd.net/hphotos-ak-xap1/v/t1.0-0/p130x130/XXXXXXXXXXX",
},
{
"name": "a photo name",
"source": "https://fbcdn-photos-b-a.akamaihd.net/hphotos-ak-xpf1/t31.0-0/p480x480/XXXXXXXXX",
"picture": "https://fbcdn-photos-b-a.akamaihd.net/hphotos-ak-xpf1/v/t1.0-0/s130x130/XXXXXXXXXXXX",
},
{
"name": "a photo name",
"source": "https://fbcdn-photos-c-a.akamaihd.net/hphotos-ak-xpa1/t31.0-0/XXXXXXXXXXX",
"picture": "https://fbcdn-photos-c-a.akamaihd.net/hphotos-ak-xpt1/v/t1.0-0/XXXXXXXXXX",
},
{
"name": "a photo name",
"source": "https://fbcdn-photos-a-a.akamaihd.net/hphotos-ak-xaf1/t31.0-0/p480x480/XXXXXXXXXX",
"picture": "https://fbcdn-photos-a-a.akamaihd.net/hphotos-ak-xat1/v/t1.0-0/s130x130/XXXXXXXX",
},
{
"name": "a photo name",
"source": "https://fbcdn-photos-b-a.akamaihd.net/hphotos-ak-xpf1/t31.0-0/p480x480/XXXXXX",
"picture": "https://fbcdn-photos-b-a.akamaihd.net/hphotos-ak-xpf1/v/t1.0-0/s130x130/XXXXXXXX",
}
],
"paging": {
"cursors": {
"before": "MTXXXXXXXXXXXXXXXgZDXXXX",
"after": "MTcXXXXXXXXXXXXXXXXXD"
}
}
},
},
{
"photos": {
"data": [
{
"source": "https://fbcdn-sphotos-e-a.akamaihd.net/hphotos-ak-xta1/v/t1.0-9/1",
"picture": "https://fbcdn-photos-a-a.akamaihd.net/hphotos-ak-xta1/v/t1.0-0/s130x130/",
},
{
"name": "XXXXXXXXXXXXXXXXX",
"source": "https://scontent.xx.fbcdn.net/v/t1.0-9/11",
"picture": "https://fbcdn-photos-c-a.akamaihd.net/hphotos-ak-xaf1/v/t1.0-0/s130x130/11",
}
],
"paging": {
"cursors": {
"before": "MOIXXXXXXXXXXXXX",
"after": "MTXXXXXXXXXXXXXD"
}
}
},
},
{
"photos": {
"data": [
{
"source": "https://fbcdn-sphotos-f-a.akamaihd.net/hphotos-ak-xpl1/t31.0-8/s720x720/",
"picture": "https://fbcdn-photos-b-a.akamaihd.net/hphotos-ak-xft1/v/t1.0-0/s130x130/",
}
],
"paging": {
"cursors": {
"before": "MTXXXXXXXXXXXSJKSDJZDZD",
"after": "MTdXXXXXXXXDKSJKDNXXXXXXXXXpZD"
}
}
},
}
],
"paging": {
"cursors": {
"before": "MXXXXXXXXXXXXXXD",
"after": "MXXXXXXXXXXXXJR"
}
}
},
"feed": {
"data": [
{
},
{
"attachments": {
"data": [
{
"media": {
"image": {
"height": 480,
"src": "https://fbcdn-sphotos-f-a.akamaihd.net/hphotos-ak-xpf1/t31.0-8/s720x720/",
"width": 720
}
}
}
]
}
},
{
"attachments": {
"data": [
{
"media": {
"image": {
"height": 102,
"src": "https://fbcdn-sphotos-e-a.akamaihd.net/hphotos-ak-xta1/v/t1.0-9/",
"width": 197
}
}
}
]
}
},
{
"attachments": {
"data": [
{
"media": {
"image": {
"height": 276,
"src": "https://fbcdn-sphotos-f-a.akamaihd.net/hphotos-ak-xpl1/t31.0-8/s720x720/",
"width": 720
}
}
}
]
}
},
{
},
{
"attachments": {
"data": [
{
"description": "XXXXXXXXXXXXKE",
"media": {
"image": {
"height": 540,
"src": "https://fbcdn-sphotos-c-a.akamaihd.net/hphotos-ak-xap1/v/t1.0-9/",
"width": 540
}
}
}
]
}
},
{
"attachments": {
"data": [
{
"description": "XXXXXXXXXXJ",
"media": {
"image": {
"height": 375,
"src": "https://scontent.xx.fbcdn.net/v/t1.0-9/",
"width": 500
}
}
}
]
}
},
{
"attachments": {
"data": [
{
"description": "XXXXXXXXXXXX",
"media": {
"image": {
"height": 540,
"src": "https://fbcdn-photos-a-a.akamaihd.net/hphotos-ak-xaf1/v/t1.0-0/p180x540/",
"width": 720
}
}
}
]
}
},
{
"attachments": {
"data": [
{
"description": "XXXXXXXXXXXXp",
"media": {
"image": {
"height": 405,
"src": "https://scontent.xx.fbcdn.net/v/t1.0-9/s720x720/",
"width": 720
}
}
}
]
}
},
{
"attachments": {
"data": [
{
"media": {
"image": {
"height": 392,
"src": "https://scontent.xx.fbcdn.net/v/t1.0-9/",
"width": 626
}
}
}
]
}
},
{
"attachments": {
"data": [
{
"description": "XXXXXXXX",
"media": {
"image": {
"height": 255,
"src": "https://fbcdn-sphotos-e-a.akamaihd.net/hphotos-ak-xpa1/v/t1.0-9/",
"width": 208
}
}
}
]
}
}
],
"paging": {
"previous": "https://graph.facebook.com/v2.5/1XXXXXXXXXXXX6/feed?fields=a",
"next": "https://graph.facebook.com/v2.5/1SXXXXXXXXXXXXX96/feed?fields="
}
},
}
I want to end up with an array like this:
Array
(
[photo] => Array
(
[0] => Array
(
[description] => a photo name
[image_src] => https://fbcdn-photos-b-a.akamaihd.net/hphotos-ak-xpf1/t31.0-0/p480x480/XXXXXX
)
[1] => Array
(
[description] => a photo name
[image_src] => https://fbcdn-photos-b-a.akamaihd.net/hphotos-ak-xpf1/t31.0-0/p480x480/XXXXXX
)
[2] => Array
(
[description] => a photo name
[image_src] => https://fbcdn-photos-b-a.akamaihd.net/hphotos-ak-xpf1/t31.0-0/p480x480/XXXXXX
)
and so on......
)
)
But I get this:
Array
(
[photo] => Array
(
[0] => Array
(
[description] => a photo name
)
[1] => Array
(
[image_src] => https://fbcdn-photos-b-a.akamaihd.net/hphotos-ak-xpf1/t31.0-0/p480x480/XXXXXX
)
[2] => Array
(
[description] => a photo name
)
[3] => Array
(
[image_src] => https://fbcdn-photos-b-a.akamaihd.net/hphotos-ak-xpf1/t31.0-0/p480x480/XXXXXX
)
and so on...
)
)
This is the code for my current loop:
foreach ($raw_facebook['albums']['data'] as $photos) {
if ($photos) {
foreach ($photos['photos']['data'] as $photo) {
if ( (isset($photo['name']) && array_key_exists('name', $photo)) && (isset($photo['source']) && $this->array_key_exists_recursive('source', $photo)) ) {
$facebook['photo'][]['description'] = $photo['name'];
$facebook['photo'][]['image_src'] = $photo['source'];
}
}
}
}
When I modify this code to this:
foreach ($raw_facebook['albums']['data'] as $photos) {
if ($photos) {
$i = 0;
foreach ($photos['photos']['data'] as $photo) {
if ( (isset($photo['name']) && array_key_exists('name', $photo)) && (isset($photo['source']) && $this->array_key_exists_recursive('source', $photo)) ) {
$facebook['photo'][$i]['description'] = $photo['name'];
$facebook['photo'][$i]['image_src'] = $photo['source'];
}
}
$i++;
}
}
I get a result similar to what I need, but with only 6 inner arrays (when there should be like 10 of them), showing the iteration isn't going correctly.
Please I'd appreciate to be pointed in the right direction.
Did this: array_push($facebook['photo'], array( 'description' => $photo['name'], 'image_src' => $photo['source'] ));
$facebook['photo'] = array();
foreach ($raw_facebook['albums']['data'] as $photos) {
if ($photos){
foreach($photos['photos']['data'] as $photo) {
if((isset($photo['name']) && array_key_exists('name', $photo)) && (isset($photo['source']) && $this->array_key_exists_recursive('source', $photo)) ){
array_push($facebook['photo'], array( 'description' => $photo['name'], 'image_src' => $photo['source'] ));
}
}
}
}
Here you go
$data = $raw_facebook['albums']['data']; //indexed array of objects
$output = array('photo' => array());
for($i = 0; $i< count($data); $i++){
$photosdataarray = $data[$i]['photos']['data'];
for($j = 0; $j < count($photosdataarray); $j++){
$output['photo'][] = array(
'description' => $photosdataarray[$j]['name'],
'image_src' => 'source',
);
}
}
Consider using collection pipeline for this kind of data processing. You'll end up with cleaner code (i.e. no foreach > if > foreach).
Example with your code (using Knapsack):
$photos = Collection::from($raw_facebook['albums']['data'])
->extract('photos.data')
->flatten(1)
->filter(function (array $data) {
return isset($data['name'])
&& isset($data['source'])
&& $this->array_key_exists_recursive('source', $data);
})
->map(function (array $data) {
return [
'description' => $data['name'],
'image_src' => $data['source']
];
})
->values()
->toArray();
Libraries:
https://dusankasan.github.io/Knapsack
https://laravel.com/docs/5.1/collections
https://github.com/cakephp/collection
I am getting a response using Unirest library, i need to separate the data, so that based on that data i can call my next query. Here is full json response i am getting while using Unirest library
echo '<pre>'; print_r($response->raw_body); echo '</pre>';
{
"status": "success",
"images": [
"http://www.example.com/12.jpg"
],
"photos": [
{
"url": "http://www.example.com/12.jpg",
"width": 205,
"tags": [
{
"confidence": 0.978945010372561,
"center": {
"y": 64,
"x": 129
},
"height": 79,
"width": 79,
"tid": "31337",
"attributes": [
{
"smile_rating": 0.56,
"smiling": true,
"confidence": 0.56
}
],
"uids": [
{
"confidence": 0.35399999999999998,
"prediction": "SE2",
"uid": "SE2#SEA1"
},
{
"confidence": 0.28999999999999998,
"prediction": "SE1",
"uid": "SE1#SEA1"
},
{
"confidence": 0.16,
"prediction": "Star1",
"uid": "Star1#SEA1"
},
{
"confidence": 0.106,
"prediction": "SE3",
"uid": "SE3#SEA1"
},
{
"confidence": 0.037999999999999999,
"prediction": "SE6",
"uid": "SE6#SEA1"
},
{
"confidence": 0.035000000000000003,
"prediction": "SE5",
"uid": "SE5#SEA1"
},
{
"confidence": 0.017999999999999999,
"prediction": "SE4",
"uid": "SE4#SEA1"
}
]
}
],
"height": 206
}
]
}
What i am trying is to print like this
Confidence : 0.35399999999999998
Similar: Test2
Well, provided it is a valid JSON string, just use a simple json_decode() with true flag so that it returns an array. Example:
$data = json_decode($response->raw_body, true);
$i = 0;
foreach($data['photos'][0]['tags'][0]['uids'] as $value) {
if($i == 5) break;
echo 'Confidence: ' . $value['confidence'] . '<br/>';
echo 'Similar: ' . $value['prediction'] . '<br/><br/>';
$i++;
}
The release of Unirest 2.0 had many improvements including ability to set custom JSON decode flags
this gives you more control over the response body type parsing method (json_decode)
Disclaimer: I'm the author of unirest-php and I work at Mashape.