Trying to unset an element from a JSON with PHP - php

I'm having some issues trying to unset a specific element from a JSON, what I have is something like that:
<?php
$json = '[{"contract":"0xb999803ee7087559eb601a4939c2d5da7668385a"},{"contract":"0x8880093d0759e485239d3010a47b80wesh5b6507daae"},{"contract":"0x77100c19ec711f0c4d6a4b38dad0b16f07aa74fe"}]';
$json_decode = json_decode($json, true);
foreach ($json_decode as $item => $value){
if ($value=='0x8880093d0759e485239d3010a47b80wesh5b6507daae')
{
unset($json_decode[$item]);
}
}
$json_decode = array_values($json_decode);
echo json_encode($json_decode);
?>
What I'd like to have afterwards is a JSON like this:
[{"contract":"0xb999803ee7087559eb601a4939c2d5da7668385a"},{"contract":"0x77100c19ec711f0c4d6a4b38dad0b16f07aa74fe"}]

Nevermind, my if statement was wrong, I had to do it like this:
if ($value['contract']=='0x8880093d0759e485239d3010a47b80wesh5b6507daae')
{
unset($json_decode[$item]);
}

Related

Using foreach Loop In PHP To Parse Json

I'm using iTunes RSS generator to get HOT tracks, now I'm using following way to parse JSON:
<?php
$json_string = 'https://rss.itunes.apple.com/api/v1/in/apple-music/hot-tracks/all/10/explicit.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
$cltn = $obj['feed']['results'][0]['collectionName'];
echo $cltn;
?>
Now, as we know that It'll return only 1 collectionName.
JSON request is returning 10 results. How can I get them all using foreach loop? I've used several ways but no success.
Since you didn't give the output of the array I assume the [0] index is what needs to be iterated.
You need to foreach the $obj['feed']['results'] by doing:
Foreach($obj['feed']['results'] as $cltn){
Echo $cltn['collectionName'];
}
Foreach over the results:
foreach ($obj['feed']['results'] as $result) {
echo $result['collectionName'] . '<br>' . PHP_EOL;
}
Based on the code you provided you can iterate the results to get all possible information from the artist/track list, for example:
$json_string = 'https://rss.itunes.apple.com/api/v1/in/apple-music/hot-tracks/all/10/explicit.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
$cltn = $obj['feed']['results'];
function test_print($item, $key)
{
echo "<strong>".$key."</strong>: ".$item."<br>";
}
foreach($cltn as $key => $c) {
echo "Result No ".($key+1)."<br>";
array_walk_recursive($c, 'test_print');
}
in case you only want to show artistName and collectionName you can slightly modify the above example:
$json_string = 'https://rss.itunes.apple.com/api/v1/in/apple-music/hot-tracks/all/10/explicit.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
$cltn = $obj['feed']['results'];
foreach($cltn as $c) {
echo $c['artistName'].": ".$c['collectionName']."<br>";
}
You can try all the above in PHP Fiddle
Try like this way with foreach() to iterate your array in key=>value manner as you've decoded the json as an array not an object in php.
<?php
$json_string = 'https://rss.itunes.apple.com/api/v1/in/apple-music/hot-tracks/all/10/explicit.json';
$jsondata = file_get_contents($json_string);
$array = json_decode($jsondata,true);
# printing resulted array just for debugging purpose
print '<pre>';
print_r($array);
print '</pre>';
foreach($array['feed']['results'] as $key=>$value){
echo $value['collectionName'].'<br/>';
}
?>

Read and print json array in php

I have a JSON array like below. I want to print only the values of the name. But I am getting undefined index name and getting value of name.below is my json.
[{"docId":{"id":"57dd70252a896558e573a0c8"},"docProfile":{"name":"gowtham","gender":null,"email":null,"mobile":"7406339908"},"docLocalInfo":{"username":"gowtham","otp":934343,"newPasswordToken":null,"tempMobile":"","adminVerfiy":null},"privateInfo":{"mciNumber":null,"aadharNumber":null,"panNumber":null},"tempHospitals":[],"bankInfo":null,"signupSteps":{"accountCreated":true,"otpValidated":true},"notification":null,"hospitals":[],"address":null}]
my code
foreach($doc_array as $data => $mydata)
{
foreach($mydata as $key=>$val)
{
echo $val['name'];
}
}
How to get the values of name from docProfile? Any help would be greatly appreciated
Inside your foreach you don't need to loop again since docProfile is an index of the json object array
Just simple access it
echo $mydata['docProfile']['name'].'<br>';
so your foreach would be like this
foreach($doc_array as $data => $mydata) {
echo $mydata['docProfile']['name'].'<br>';
}
Demo
Try to something Like this.
<?php
$string = '[{"docId":{"id":"57dd70252a896558e573a0c8"},"docProfile":{"name":"gowtham","gender":null,"email":null,"mobile":"7406339908"},"docLocalInfo":{"username":"gowtham","otp":934343,"newPasswordToken":null,"tempMobile":"","adminVerfiy":null},"privateInfo":{"mciNumber":null,"aadharNumber":null,"panNumber":null},"tempHospitals":[],"bankInfo":null,"signupSteps":{"accountCreated":true,"otpValidated":true},"notification":null,"hospitals":[],"address":null}]';
$arr = json_decode($string, true);
echo $arr[0]['docProfile']['name'];
?>
This array just have one row but if your array have more row you can use it;
you need to decode JSON at first.
$doc_array =json_decode($doc_array ,true);
foreach($doc_array as $key=> $val){
$val['docProfile']['name']
}
<?php
$json_str='[{"docId":{"id":"57dd70252a896558e573a0c8"},"docProfile":{"name":"gowtham","gender":null,"email":null,"mobile":"7406339908"},"docLocalInfo":{"username":"gowtham","otp":934343,"newPasswordToken":null,"tempMobile":"","adminVerfiy":null},"privateInfo":{"mciNumber":null,"aadharNumber":null,"panNumber":null},"tempHospitals":[],"bankInfo":null,"signupSteps":{"accountCreated":true,"otpValidated":true},"notification":null,"hospitals":[],"address":null}]';
$json_arr = (array)json_decode($json_str,true);
foreach($json_arr as $iarr => $ia)
{
foreach($ia["docProfile"] as $doc => $docDetails)
{
if($doc =="name")
{
echo $ia["docProfile"]["name"];
}
}
}
?>
This code gives you the answer

JSON decode in php web programming

I am facing a problem in php using CURL. I made a https request and I got response in multidimesional array.
[{
"id":"22622",
"name":"",
"email":"ffv7678#gmail.com",
"mobileno":"",
"birth_dt":"",
"marital_status":"",
"gender":"",
"educationid":"0",
"occupationid":"0",
"industryid":"0",
"incomeid":"",
"city":"0",
"state":"0",
"country":"0",
"postcode":"",
"deviceid":"805086099499488",
"regid":"",
"device_type":null,
"userstatus":"0",
"refcode":"D1219C92",
"new_user":"0",
"device_token":""
}]
Now I want to decode it and save the value of "id" in a variable.
$result=curl_exec($ch);
$books = json_decode($result, true);
echo ($books[0]['id']);
I tried the above code, but failed.
$books = json_decode($result, true);
foreach ($books as $book)
{
//$book carries info of books;
$id = $book['id'];
///... You can define other variables here
}
You need to use foreach() loop for this.
foreach ($a[0] as $key => $value) {
echo $key."<br>".$value;
if($key == 'id'){
$id = $value;
}
}
echo $id;
Also, if you just want to assign the value of id to another variable, you can just right
...
$no = $a[0]->id;
echo $no
...
instead of the foreach loop.

Loop through JSON and store values to PHP arrays

I have a JSON with the Following structure.
{
"1":{"Itemname":"dtfg","unitprice":"12","Qty":"4","price":"$48.00"},
"2":{"Itemname":"kjh","unitprice":"45","Qty":"7","price":"$315.00"},
"3":{"Itemname":"yjk","unitprice":"76","Qty":"8","price":"$608.00"},
"4":{"Itemname":"hgj","unitprice":"4","Qty":"45","price":"$180.00"}
}
I need the Itemname to be made into a PHP array, Unitprice into another one, Qty to another one and price to another one. How do I do that?
$getArray = get_object_vars(json_decode($json));
print_r($getArray);
echo $getArray[1]->Itemname;
echo $getArray[1]->unitprice;
you require get_object_vars as well for achieving your requirement.
<?php
$json =<<<JSONLIVES
{
"1":{"Itemname":"dtfg","unitprice":"12","Qty":"4","price":"$48.00"},
"2":{"Itemname":"kjh","unitprice":"45","Qty":"7","price":"$315.00"},
"3":{"Itemname":"yjk","unitprice":"76","Qty":"8","price":"$608.00"},
"4":{"Itemname":"hgj","unitprice":"4","Qty":"45","price":"$180.00"}
}
JSONLIVES;
$items = json_decode($json, TRUE);
$item_names = array();
foreach($items as $key => $item) {
$item_names[] = $item['Itemname'];
}
Or Php >= 5.5
print_r(array_column($items, 'Itemname'));
You need a function called json_decode() to convert your json data into PHP array
$json = {
"1":{"Itemname":"dtfg","unitprice":"12","Qty":"4","price":"$48.00"},
"2":{"Itemname":"kjh","unitprice":"45","Qty":"7","price":"$315.00"},
"3":{"Itemname":"yjk","unitprice":"76","Qty":"8","price":"$608.00"},
"4":{"Itemname":"hgj","unitprice":"4","Qty":"45","price":"$180.00"}
};
var_dump(json_decode($json));
You need to decode your Json by PHP's json_decode()
$decodeJson will return object then you can read Itemname and other values by using $val->Itemname in foreach loop
$json = '{
"1":{"Itemname":"dtfg","unitprice":"12","Qty":"4","price":"$48.00"},
"2":{"Itemname":"kjh","unitprice":"45","Qty":"7","price":"$315.00"},
"3":{"Itemname":"yjk","unitprice":"76","Qty":"8","price":"$608.00"},
"4":{"Itemname":"hgj","unitprice":"4","Qty":"45","price":"$180.00"}
}';
$decodeJson = json_decode($json);
foreach($decodeJson as $key=>$val) {
print_r($val);
}
Live Json decode
Try that:
$json = json_decode($json);
foreach($json as $obj){
echo $obj->name;
.....
}
After some research, I found out that the most efficientt way that solves my problem here would be to do like the following.
$cash=json_decode($new_json, true);
echo $arr3[1]['Itemname'];
echo $arr3[1]['unitprice'];
:
:
and so on.
This can be put into loops easily, fetched into HTML text-fields (as I want here in this scenario) and so on.

JSON search event names and list URL values

I'm loading event listing as an JSON-File from an URL:
$file = file_get_contents('http://ecample.com/listing.php?');
$data = json_decode($file);
?>
The direct output looks like this (more values and mor lines):
[{"id":"1","name":"NAME_1","booking_url":"https://ecample.com/Event_ID65654","category_id":"195"},
{"id":"2","name":"NAME_2","booking_url":"https://ecample.com/Event_ID65654","category_id":"195"},
"id":"1","name":"NAME_1","booking_url":"https://ecample.com/Event_ID65654","category_id":"195"}]
I need to search for all entrys with the value "name":"NAME_1" and print out the value of "booking_url".
I tried different things like array_seach() etc. but did not work out.
Any help is appreciated!
try this
<?php
$file = file_get_contents('http://ecample.com/listing.php?');
$data = json_decode($file, true);
foreach ($data as $r)
{
if ($r['name'] == 'NAME_1')
{
echo $r['booking_url'];
}
}
?>
The other option is to access your data in object context, thus:
<?php
$file = file_get_contents('http://ecample.com/listing.php?');
$data = json_decode($file);
foreach ($data as $r)
{
if ($r->name == 'NAME_1')
{
echo $r->booking_url;
}
}
?>
Either one should work just as well.

Categories