php foreach nested loop retrieve all records - php

$json_string = '{
"response_code": 200,
"info": {
"days": [
{
"code": "A",
"runs": "111"
},
{
"code": "B",
"runs": "222"
},
{
"code": "C",
"runs": "333"
}
],
"name": "SUPER MARIO",
"number": "010203",
"classes": [
{
"points": "6523",
"name": "ABC",
"available": "N"
},
{
"points": "4253",
"name": "XYZ",
"available": "N"
},
{
"points": "2323",
"name": "JOHN",
"available": "N"
},
{
"points": "5236",
"name": "TAMIL",
"available": "N"
}
]
}
}';
$jsondata = $json_string;
$arr = json_decode($jsondata, true);
foreach($arr as $k=>$v)
{
echo $k."<br>";
}
it prints
response_code
info
But, I need the results like this
6523 ABC
4253 XYZ
2323 JOHN
5326 TAMIL
I have tried and achieved this above results using this below code. But, I want to do it using foreach loop. How do list out all information using foreach?
echo "".$arr['info']['classes'][0]['points']." ".$arr['info']['classes'][0]['name']."<br/>";
echo "".$arr['info']['classes'][1]['points']." ".$arr['info']['classes'][1]['name']."<br/>";
echo "".$arr['info']['classes'][2]['points']." ".$arr['info']['classes'][2]['name']."<br/>";
echo "".$arr['info']['classes'][3]['points']." ".$arr['info']['classes'][3]['name']."<br/>";

You should foreach your array key
foreach($arr['info']['classes'] as $k=>$v)
{
echo $v['points']." " . $v['name']."<br>";
}

Related

Parsing Json into php table results in Undefined index

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

Display value of json to output

Below is json code where i have o display its values. How to fetch the output as given below
$jsondata = '{
"flowers": [
{
"id": "1",
"name": "Le Grand Bouquet Blanc",
"price": "65",
"currency": "euro"
},
{
"id": "2",
"name": "Roses",
"price": "33",
"currency": "euro"
},
{
"id": "3",
"name": "Mandarine",
"price": "125",
"currency": "euro"
}
]
}';
Output should come like this
Name : Le Grand Bouquet Blanc, Price : 65
Name : Roses, Price : 33
Name : Mandarine, Price : 125
Total: 223 Euro
Any Help?
JSON decode, loop through the data and output the required text like so:
$data = json_decode($jsondata);
$total = 0;
foreach($data->flowers as &$datum) {
printf('Name : %s, Price: %d'.PHP_EOL, $datum->name, $datum->price);
$total += $datum->price;
}
printf('Total: %d Euro'.PHP_EOL, $total);
Read up on some basic PHP functions/concepts:
http://php.net/manual/en/function.json-decode.php
http://php.net/manual/en/control-structures.foreach.php
http://php.net/manual/en/function.printf.php
http://php.net/manual/en/function.echo.php
http://php.net/manual/en/language.operators.arithmetic.php
Try using json_decode() with true as second attribute to convert JSON it into array first.Then use foreach loop and get desired result.
<?php
$jsondata = '{
"flowers": [
{
"id": "1",
"name": "Le Grand Bouquet Blanc",
"price": "65",
"currency": "euro"
},
{
"id": "2",
"name": "Roses",
"price": "33",
"currency": "euro"
},
{
"id": "3",
"name": "Mandarine",
"price": "125",
"currency": "euro"
}
]
}';
$array = json_decode($jsondata,true);
//print_r($array);
$sum = 0;
foreach($array['flowers'] as $flowers)
{
echo "Name : ".$flowers['name'].",Price : ".$flowers['price'].PHP_EOL;
$sum+=$flowers['price'];
$currency = $flowers['currency'];
}
echo "Total:".$sum." ".$currency;
Try this.
$jsondata = '{
"flowers": [
{
"id": "1",
"name": "Le Grand Bouquet Blanc",
"price": "65",
"currency": "euro"
},
{
"id": "2",
"name": "Roses",
"price": "33",
"currency": "euro"
},
{
"id": "3",
"name": "Mandarine",
"price": "125",
"currency": "euro"
}
]
}';
$data = json_decode($jsondata,true);
echo "Name : " . $data['flowers'][0]['name'] . ' , Price: ' . $data['flowers'][0]['price'] ;

Display some parts of a file written in json

Below is my JSON file:
{
"example": "1",
"example2": 2,
"text": "3",
"info": {
"agent": 4,
"sum": 5,
"collection": [{
"Name": "6",
"Pic": "7"
} {
"Name": "8",
"Pic": "9"
}, {
"Name": "10",
"Pic": "11"
}]
}
}
How would I display each 'name' and 'pic' I think I need to use a foreach loop but don't know how to.
This is all the code I have:
$data = json_decode(file_get_contents('http://linktojson.com'));
echo $data['info']['collection'][0]['Name'];
echo $data['info']['collection'][0]['Pic'];
This should work
$data = json_decode(file_get_contents('http://linktojson.com'));
echo "<pre>".print_r($data,1)."</pre>";
foreach($data->info->collection as $key){
echo $key->Pic;
echo $key->Name;
}
Valid JSON
{
"example": "1",
"example2": 2,
"text": "3",
"info": {
"agent": 4,
"sum": 5,
"collection": [{
"Name": "6",
"Pic": "7"
}, {
"Name": "8",
"Pic": "9"
}, {
"Name": "10",
"Pic": "11"
}]
}
}

Parsing an array with PHP in a foreach loop

I want to parse an array with PHP's foreach loop to get the object names and values inside the 'ques' array.
[
{
"ques": [
{
"name": "comment",
"value": "comment me for the reason",
"sur_id": "1",
"user_id": "admin#gmail.com",
"pagename": "question_response"
},
{
"name": "check-box[]",
"value": "1"
},
{
"name": "radio",
"value": "radio 2"
},
{
"name": "yes",
"value": "no"
}
]
"ques":[
{
"name": "date",
"value": "2015-10-23"
},
{
"name": "select-deopdown",
"value": ""
},
{
"name": "true",
"value": "false"
},
{
"name": "number",
"value": "55"
}
]
}
]
I want to separate the value from the 'ques' array:
while ($fetch = mysql_fetch_array($query1)) {
$content = $fetch['CONTENT_VALUES'];
// print_r($content);
$content_value= mb_convert_encoding($content ,"UTF-8");
$datas = json_decode($content, true);
foreach($datas->ques as $values)
{
echo $values->value . "\n";
print_r($values);
}
$test[] = array('ques' => $datas ,'answer'=>$values);
}

group elements inside a json

I'm trying to make a json that looks like this:
{
"data": {
"error_message": "",
"data": {
"person": [
[
{
"name": "teset1",
"image": "http://test.co.il/test/icons/billadress.png"
},
{
"name": "test2",
"image": "http://test.co.il/test/icons/email.png"
},
{
"name": "test3",
"image": "http://test.co.il/test/icons/homeicon.png"
}
],
[
{
"name": "a",
"image": "http://test.co.il/shay/keykit/icons/billadress.png"
},
{
"name": "b",
"image": "http://test.co.il/shay/keykit/icons/email.png"
},
{
"name": "c",
"image": "http://dvns.co.il/shay/keykit/icons/homeicon.png"
}
],
[
{
"name": "a",
"image": "http://test.co.il/test/icons/billadress.png"
},
{
"name": "b",
"image": "http://test.co.il/test/icons/email.png"
},
{
"name": "c",
"image": "http://dvns.co.il/test/icons/homeicon.png"
}
],
]
}
},
}
This is the code i'm using after i'm getting the name & image from the mysql query:
$response = $this->_db->query($query)->result_array();
$icons_results = array();
$obj = new stdclass();
foreach ($response as $key => $response) {
$icons_model = new icons_model();
$icons_model->init($response);
$obj->families[] = $icons_model;
}
return $obj;
SO .. this is what i'm getting:
{
"data": {
"families": [
{
"id": "1",
"name": "a",
"image_url": "http://test.co.il/shay/keykit/icons/billadress.png"
},
{
"id": "2",
"name": "b",
"image_url": "http://test.co.il/shay/keykit/icons/email.png"
},
{
"id": "3",
"name": "c",
"image_url": "http://test.co.il/test/icons/homeicon.png"
},
{
"id": "6",
"name": "f",
"image_url": "http://test.co.il/test/icons/homeicon.png"
},
{
"id": "4",
"name": "d",
"image_url": "http://test.co.il/test/icons/billadress.png"
},
{
"id": "5",
"name": "e",
"image_url": "http://test.co.il/test/icons/billadres2323s.png"
},
and do on.
How to i make that every three object will be in a group? (like the first example)
Try this:
foreach ($response as $key => $response) {
$icons_model = new icons_model();
$icons_model->init($response);
$obj->families[(int)($key / 3)][] = $icons_model;
}

Categories