Remove the last charater from string which is generated in loop - php

Believe me, I have tried everything that is there in stack overflow!
So, I got this JSON -
$j={
"itempicture": [
{
"status": "3"
},
{
"ItemCode": "001",
"ItemImage": "image1",
"ItemCategory": "shirt",
"ShowOnPOS": "Yes",
"LastModifiedOn": "2018-06-02 11:53:57"
},
{
"ItemCode": "002",
"ItemImage": "image2",
"ItemCategory": "shirt",
"ShowOnPOS": "Yes",
"LastModifiedOn": "2018-06-02 11:53:57"
}
]
}
and i am accessing it like this -
$jo = json_decode($j);
for($i = 1; $i < count($jo->itempicture); $i++) {
foreach($jo->itempicture[$i] as $prop=>$val) {
echo $val.",";
}
echo '<br>';
}
and I'm getting this output -
001,image1,shirt,Yes,2018-06-02 11:53:57,
002,image2,shirt,Yes,2018-06-02 11:53:57,
The main prob with this output is the "," at the last.
I am unable to remove it!
Tried everything -
This -
Remove the last character from string
with substr, rtrim, implode...
EVERYTHING!
It's not working!

A version using implode() which means that you have to convert from JSON into arrays (the default is to convert to objects, so add true as second paramter to json_decode()).
$j='{"itempicture":[
{
"status":"3"
},
{
"ItemCode":"001",
"ItemImage":"image1",
"ItemCategory":"shirt",
"ShowOnPOS":"Yes",
"LastModifiedOn":"2018-06-02 11:53:57"
},
{
"ItemCode":"002",
"ItemImage":"image2",
"ItemCategory":"shirt",
"ShowOnPOS":"Yes",
"LastModifiedOn":"2018-06-02 11:53:57"
}
]
}';
$jo=json_decode($j, true);
array_shift($jo['itempicture']);
$edata = '';
foreach ( $jo['itempicture'] as $item) {
$edata .= implode(",", $item).'<br/>';
}
echo "<pre>";
print_r($edata);
echo "</pre>";
Prints out...
<pre>001,image1,shirt,Yes,2018-06-02 11:53:57<br/>
002,image2,shirt,Yes,2018-06-02 11:53:57<br/></pre>

Here is the solution
$j='{"itempicture":[
{
"status":"3"
},
{
"ItemCode":"001",
"ItemImage":"image1",
"ItemCategory":"shirt",
"ShowOnPOS":"Yes",
"LastModifiedOn":"2018-06-02 11:53:57"
},
{
"ItemCode":"002",
"ItemImage":"image2",
"ItemCategory":"shirt",
"ShowOnPOS":"Yes",
"LastModifiedOn":"2018-06-02 11:53:57"
}
]
}';
$jo=json_decode($j);
$edata = '';
for($i=1;$i<count($jo->itempicture);$i++){
$data = '';
foreach($jo->itempicture[$i] as $prop=>$val){
$data .= $val.",";
}
$edata .= rtrim($data, ",");
$edata .='<br/>';
}
echo "<pre>";
print_r($edata);
echo "</pre>";

You could do something like this
$jo=json_decode($j);
for($i=1;$i<count($jo->itempicture);$i++){
foreach($jo->itempicture[$i] as $prop=>$val){
if ($value === end($jo->itempicture[$i])) {
echo $val;
}
else {
echo $val.",";
}
}
echo '<br>';
}
That would prevent from writing the last ',' by comparing if your current iteration is the end of the loop

If you know that the last element would always be LastModifiedOn
$jo=json_decode($j);
for($i=1;$i<count($jo->itempicture);$i++){
foreach($jo->itempicture[$i] as $prop=>$val){
if($prop == "LastModifiedOn")
echo $val;
else
echo $val.",";
}
echo '<br>';
}

Related

Not able to parse nested Json array in PHP while print_r function is printing all values properly

I am trying to parse a json array string. Though print_r prints all the values properly but while fetching the records I failed.
I must be doing something very terribly wrong. Could you please help to correct it.
So here is my code
<?
$str ='
{
"tenant_view_details": [
{
"status":"S",
"tenant_general":[
{"tenant_id":"6003","code":"ICI001","type":"BANK","category":"SM","gstn":"IWSDFS7372","pan":"KSAH9876AS","cin":"ASHED456","name":"ICICI Bank","address_line_1":"23, Hertz Plaza, Rajiv Chowk","address_line_2":" ","address_city":"New Delhi","address_distict ":"New Delhi","address_state ":"DL","address_state_code ":"07","address_pin ":"119923","contact_name ":"contact_name","contact_phone ":"1234567890","contact_std_code ":"11","contact_landline ":"1234567890","contact_email_id ":"contact#email.com"} ],
"tenant_bank": [
{ "bank_name ":"xyz","bank_account_no ":"12345","account_type ":"abc","ifsc_code ":"xx123","address_line_1 ":"qwer","address_line_2 ":"23","address_city ":"abc","address_district ":"xyz","address_state_name ":"asd","address_state_code ":"02","address_pin ":"123456" } ],
"tenant_agreement": [
{ "category ":"OM","tenancy_type ":"EXT","echarge_type ":"FIX","total_tenancy_value ":"32900.00","energy_charge_value ":"16543.00","rev_share_pct ":"0.05","start_dt":"10-1-2018","end_dt":"31-12-2020","attachment_path ":"na","change_value ":"na","latest_flag ":"Y","w_status ":"20","status ":"ACT"} ],
"tenant_sites": [
{"tenant_id":"6003","site_master_id":"1020","tn_site_code":"UPWMORA00069473","tn_site_name":"Deendayal Nagar","tn_cluster":"CLUSTER-03","circle_code":"UW","tower_type":"MAST","site_type":"ID","tenancy_type":"EXT","echarge_type":"FIX","primary_tenant":"N","latest_flag ":"Y"}, {"tenant_id":"6003","site_master_id":"1019","tn_site_code":"UPWGHAZ00069467","tn_site_name":"DJ College Newari Road, Modina","tn_cluster":"CLUSTER-03","circle_code":"UW","tower_type":"MAST","site_type":"ID","tenancy_type":"EXT","echarge_type":"FIX","primary_tenant":"N","latest_flag ":"Y"}, {"tenant_id":"6003","site_master_id":"1018","tn_site_code":"UPWMORA00069464","tn_site_name":"Bazar Makhbra","tn_cluster":"CLUSTER-03","circle_code":"UW","tower_type":"RTT","site_type":"OD","tenancy_type":"EXT","echarge_type":"FIX","primary_tenant":"N","latest_flag ":"Y"}, {"tenant_id":"6003","site_master_id":"1016","tn_site_code":"UPWGHAZ00069454","tn_site_name":"Hoshdarpur Garhi","tn_cluster":"CLUSTER-03","circle_code":"UW","tower_type":"RTT","site_type":"OD","tenancy_type":"EXT","echarge_type":"FIX","primary_tenant":"N","latest_flag ":"Y"}, {"tenant_id":"6003","site_master_id":"1011","tn_site_code":"UPWMUZN00069430","tn_site_name":"Sikanderpur","tn_cluster":"CLUSTER-03","circle_code":"UW","tower_type":"RTT","site_type":"ID","tenancy_type":"EXT","echarge_type":"FIX","primary_tenant":"N","latest_flag ":"Y"}, {"tenant_id":"6003","site_master_id":"1008","tn_site_code":"UPWALIG00069299","tn_site_name":"Mukund Vihar","tn_cluster":"CLUSTER-03","circle_code":"UW","tower_type":"RTT","site_type":"","tenancy_type":"EXT","echarge_type":"FIX","primary_tenant":"N","latest_flag ":"Y"} ]
}
]
}
';
$dataset = json_decode($str, true);
//print_r ($dataset);
foreach ($dataset['tenant_view_details'] as $newdata) {
$general = $newdata['tenant_general'];
$bank = $newdata['tenant_bank'];
$agreement = $newdata['tenant_agreement'];
$sites = $newdata['tenant_sites'];
}
//prinitng data
echo "<br/>";
print_r($general);
echo "<br/>";
print_r($bank);
echo "<br/>";
print_r($agreement);
echo "<br/>";
foreach($general as $general_data){
(isset($general_data['tenant_id']) && !empty($general_data['tenant_id']))? $tenant_id=$general_data['tenant_id'] : $tenant_id="not set";
echo "<br/>tenant_id::" . $tenant_id;
}
foreach($bank as $bank_data){
(isset($bank_data['bank_name']) && !empty($bank_data['bank_name']))? $bank_name=$bank_data['bank_name'] : $bank_name="not set";
echo "<br/>bank_name:" . $bank_data['bank_name'];
}
foreach($agreement as $agreement_data){
(isset($agreement_data['category']) && !empty($agreement_data['category']))? $category=$agreement_data['category'] : $category="not set";
(isset($agreement_data['tenancy_type']) && !empty($agreement_data['tenancy_type']))? $tenancy_type=$agreement_data['tenancy_type'] : $tenancy_type="not set";
(isset($agreement_data['echarge_type']) && !empty($agreement_data['echarge_type']))? $echarge_type=$agreement_data['echarge_type'] : $echarge_type="not set";
echo "<br/>category:" . $category;
echo "<br/>tenancy_type:" . $tenancy_type;
echo "<br/>echarge_type:" . $echarge_type;
}
?>
Your problem is that in your $bank and $category arrays, all the keys have trailing spaces on them. If you change the references to include those spaces, your code works fine. See https://3v4l.org/GX5iC
Alternatively you can trim the array keys, using something like this code inside your foreach loops:
$bank_keys = array_map('trim', array_keys($bank_data));
$bank_data = array_combine($bank_keys, array_values($bank_data));
You could also create a recursive function to trim the entire $dataset value. For example:
function trim_keys($array) {
foreach ($array as $key => $value) {
echo "trimming key '$key' to '" . trim($key) . "'\n";
unset($array[$key]);
$array[trim($key)] = $value;
if (is_array($value))
$array[trim($key)] = trim_keys($value);
else
$array[trim($key)] = $value;
}
return $array;
}
Then, by using
$dataset = trim_keys($dataset);
Your code will work fine. Demo on 3v4l.org

please help to parse json

JSON:
{
"hashrate": 551125275,
"miners": {
"0x0916c53bc9c5a934f9b3dc1b01abd56241569977": {
"lastBeat": 1538180874,
"hr": 139778683,
"offline": false
},
"0x3382e1265913d1f8161ead5422b7ca1e7cd80fc6": {
"lastBeat": 1538180856,
"hr": 22072348,
"offline": false
}
},
"minersTotal": 2,
"now": 1538180878485
}
I want to get like this:
Account1:0x0916c53bc9c5a934f9b3dc1b01abd56241569977
Account2:0x3382e1265913d1f8161ead5422b7ca1e7cd80fc6
$json = ' {
"hashrate": 551125275,
"miners": {
"0x0916c53bc9c5a934f9b3dc1b01abd56241569977": {
"lastBeat": 1538180874,
"hr": 139778683,
"offline": false
},
"0x3382e1265913d1f8161ead5422b7ca1e7cd80fc6": {
"lastBeat": 1538180856,
"hr": 22072348,
"offline": false
}
},
"minersTotal": 2,
"now": 1538180878485
}';
$data = json_decode($json);
$i = 1;
foreach ($data->miners as $key => $value) {
echo 'Account' . $i++ . ':' . $key . PHP_EOL;
}
The easiest way to work with JSON in PHP is using the JSON extension. See http://php.net/manual/en/book.json.php
So you can convert a JSON string to stdClass and vice-versa.
Like this:
$json_object = json_decode($json_string);
var_dump($json_object->miners);

Adding key in an Array PHP

Im studying in array, and I was wondering How can I add key to this kind of array?
{
"items":[
{
"count":"1",
"id":123,
"description":"Bag",
"price":11
},
{
"count":1,
"id":1234,
"description":"10% Discount",
"price":-1.1
}
],
"total":9.9,
"discount_total":9.9
}
because I needed convert the array to have a key base on the id inside the array.
{
"items":{
"123":{
"count":"1",
"cart_id":123,
"description":"Bag",
"price":11
},
"1234":{
"count":1,
"cart_id":1234,
"description":"10% Discount",
"price":-1.1
}
},
"total":9.9,
"discount_total":9.9
}
and this is my code
header('Content-Type: application/json');
$cart_array = json_decode('{
"items":[
{
"count":"1",
"cart_id":123,
"plu":"TP16",
"description":"Bag"
},
{
"count":1,
"cart_id":1234,
"plu":"DISCT10",
"description":"10% Discount"
}
],
"total":9.9,
"discount_total":9.9
}');
foreach ($cart_array->items as $item)
{
$construct["cart_id"] = $item->cart_id;
}
I wanted to ask how can I put the id in the array? I cant use $cart_array['id'] = $value, it returns error.
Uncaught Error: Cannot use object of type stdClass as array
I could really use some explanation here
Following code can help you.
<?php
$json = '{
"items":[
{
"count":"1",
"cart_id":123,
"plu":"TP16",
"description":"Small Four Seasons"
},
{
"count":1,
"cart_id":1234,
"plu":"DISCT10",
"description":"10% Discount"
}
],
"total":9.9,
"discount_total":9.9
}';
$data = json_decode($json,TRUE); //json decode
foreach ($data['items'] as $key => $value)
{
$data['items'][$value['cart_id']] = $value;
unset($data['items'][$key]);
}
echo "<pre>";print_r($data);die;
?>
You don't have to loop at all. You can use array_column to make an array associative with one line of code.
$cart_array['items'] = array_column($cart_array['items'], NULL, 'cart_id');
https://3v4l.org/cPD5n
You can use this code in your application to add keys to indexed array.
foreach($obj as $key=>$val){
foreach ($val as $index=>$content){
$data[$content['id']]=$content;
}
}
You can get same output json data as per you want :
$array = json_decode($data,true);
if(isset($array['items']) && count($array['items']) > 0){
foreach($array['items'] as $key => $value){
$value['cart_id'] = $value['id'];
unset($value['id']);
$array['items'][$value['cart_id']] = $value;
unset($array['items'][$key]);
}
}
echo "<pre>";print_r($array);
echo json_encode($array);

trying to get multiple nested values from jagged json array using json_decode

I'm trying to print the url and filename of the files array inside each instance that is shown. Each for instance
http://xbins.nyc/mvscu
mvscu.zip
http://xbins.nyc/mvsc
mvsc.zip
http://xbins.nyc/mvscjp
mvscjp.zip
The above is how the output should be once the code below runs. it throws errors since it's checking the whole code for the further nested arrays.
{
"accountId":"Ja4Rulez",
"finished":"true",
"createdAt":"2016-05-20",
"releaseDate":"1998",
"updatedAt":"2016-05-20",
"expires":"1468905126822",
"requestTableUS":{
"tableCAPCOM":{
"tableName":"CAPCOM",
"partial":"true",
"files":[
{
"url":"http://xbins.nyc/mvscu",
"filename":"mvscu.zip"
}
]
}
},
"requestTableMain":{
"tableCAPCOM":{
"tableName":"CAPCOM",
"partial":"true",
"files":[
{
"url":"http://xbins.nyc/mvsc",
"filename":"mvsc.zip"
}
]
}
},
"requestTableJp":{
"tableCAPCOM":{
"tableName":"CAPCOM",
"partial":"true",
"files":[
{
"url":"http://xbins.nyc/mvscjp",
"filename":"mvscjp.zip"
}
]
}
}
}
The above query is sent to the $data variable below and then json_decoded into $obj.
<?php
$obj = json_decode($data, TRUE);
foreach($obj as $row){
foreach($row as $k){
foreach($k as $j){
foreach($j as $l){
echo $l['url'];
echo "<br />";
echo $l['filename'];
echo "<br />";
}
}
}
}
?>
Also the number of returned "requestTable"s returned vary but here it's simply 3, but it can change from 3 to 100+. I need to make sure the loop can accommodate additional "requestTables" if available.
Most of the elements of $obj are not arrays, so you can't use foreach on them. You only want to drill down into the elements whose keys begin with requestTable, and then you only want to loop through the files, not everything in that element.
foreach ($obj as $key => $row) {
if (substr($key, 0, 12) == 'requestTable')) {
foreach ($row['tableCAPCOM']['files'] as $l) {
echo $l['url'];
echo "<br />";
echo $l['filename'];
echo "<br />";
}
}
}
This snippet should do exactly what you want.
<?php
$array = json_decode($json, true);
foreach($array as $key=>$data) {
if (strpos($key, 'requestTable') !== false) {
foreach($data['tableCAPCOM']['files'] as $file) {
echo $file['url'];
echo "<br />";
echo $file['filename'];
echo "<br />";
}
}
}
?>

PHP echo JSON nested array values

I want to echo all expanded_url and urls. echo $name prints results . echo $value doesn't print anything because of nested array. How do I echo all values?
$json ='{ "results" : [ { "entities" :
[ { "urls" : [ { "expanded_url" : "http://www.google.com",
"url" : "http://t.co/WZnUf68j"
}, { "expanded_url" : "http://www.facebook.com",
"url" : "http://t.co/WZnUf68j"
}, { "expanded_url" : "http://www.twitter.com",
"url" : "http://t.co/WZnUf68j"
} ] } ],
"from_user" : "A-user-name",
"from_user_id" : 457304735,
"text" : "Ich R U #BoysNoize #SuperRola"
} ] }';
# $json_array = (array)(json_decode($json));
$data = json_decode($json,true);
foreach($data as $name => $value){
echo $name.'<br>';
echo $value; // NOT WORKING - HOW TO ECHO ALL VALUES
}
You can do that with
$data = json_decode($json,true);
foreach($data["results"][0]["entities"][0]["urls"] as $value){
echo $value['expanded_url']."\n";
echo $value['url']."\n";
}
Since it's a multidimensional array, you can loop through the various levels to reach where you want.
foreach($data['results'] as $item) {
foreach($item['entities'] as $urls) {
foreach($urls['urls'] as $element) {
echo "expanded_url: {$element['expanded_url']} \n";
echo "url: {$element['url']} \n";
}
}
}
Note: The reason I've done the various foreach loops is due to the fact that there may be different results or different entities, so it's better to loop, than to do foreach($data["results"][0]["entities"][0]["urls"] as $value)
Example

Categories