php - Accessing json array object - php

I have a JSON array object in which I am trying to append an array to one of the fields.
{"email":"bar#foo.org","password":"password","devices":{}}
print_r($arr) gives me:
Array ( [0] => {
"email":"bar#foo.org",
"password":"password",
"devices":{}
}
[1] => {
"email":"bar2#foo.org",
"password":"password",
"devices":{}
}
)
where $device_info is an array of structure:
array(
"number" => $phoneNumber,
"type" => "CellPhone",
"config" => array(
"batteryLevel" => 100,
"Lowbatterylevel" => 10,
)
I am trying to do this:
array_push($arr[$i]["devices"],$device_info);
which throws an error "Warning: Illegal string offset 'devices' "
I saw some other similar questions in StackOverflow but the solutions didn't work. Can someone point out what I'm doing wrong here? Thanks in advance.

You are not looking closely enough at your original JSON String or the full output from your print_r()
That is an Object containing properties and devices property is an object as well that contains it own properies
Here is some sample code to get your going
$s = '{"email":"bar#foo.org","password":"password","devices":{}}';
$j = json_decode($s);
$o = new stdClass();
$o->number = 999;
$o->type = "CellPhone";
$o->config = array("batteryLevel" => 100,"Lowbatterylevel" => 10);
$j->devices = $o;
print_r($j);
echo json_encode($j);
Results are
stdClass Object
(
[email] => bar#foo.org
[password] => password
[devices] => stdClass Object
(
[number] => 999
[type] => CellPhone
[config] => Array
(
[batteryLevel] => 100
[Lowbatterylevel] => 10
)
)
)
{"email":"bar#foo.org","password":"password","devices":{"number":999,"type":"CellPhone","config":{"batteryLevel":100,"Lowbatterylevel":10}}}

To me this looks like you confuse objects and arrays in your approach...
That json encoded string you posted does not encode an array but an object. So you have to treat it as such. Take a look at this simple demonstration code:
<?php
$payload = [
"number" => '01234567890',
"type" => "CellPhone",
"config" => [
"batteryLevel" => 100,
"Lowbatterylevel" => 10
]
];
$input = '{"email":"bar#foo.org","password":"password","devices":{}}';
$data = json_decode($input);
$data->devices = $payload;
$output = json_encode($data);
print_r(json_decode($output));
print_r($output);
The output ob above obviously is:
stdClass Object
(
[email] => bar#foo.org
[password] => password
[devices] => stdClass Object
(
[number] => 01234567890
[type] => CellPhone
[config] => stdClass Object
(
[batteryLevel] => 100
[Lowbatterylevel] => 10
)
)
)
{"email":"bar#foo.org","password":"password","devices":{"number":"01234567890","type":"CellPhone","config":{"batteryLevel":100,"Lowbatterylevel":10}}}

Related

How do I get an element from JSON in PHP?

I have this output from a JSON. How can I get one element (for example "etternavn" ) into a PHP variable. This is the output I get for the whole thing:
stdClass Object (
[hitLinesBeforeFilter] => 1
[userID] => 632
[1] => stdClass Object (
[listing] => stdClass Object (
[table] => listing
[id] => 1402864
[duplicates] => Array (
[0] => stdClass Object (
[table] => listing
[id] => 1402864:0
[idlinje] => D1FIJFT000
[tlfnr] => 41428798
[etternavn] => Bumpy Bones Interactive Cornelius Gutsu
[veinavn] => Hans Nielsen Hauges vei
[husnr] => 48F
[postnr] => 1523
[virkkode] => N
[apparattype] => M
[kilde] => D
[foretaksnr] => 998209609
[bransjekode] => 15636
[prioritet] => 0
[kommunenr] => 104
[poststed] => Moss
[kommune] => Moss
[fylke] => Østfold
[landsdel] => Ø
[bransjebokmaal] => Internettdesign og programmering
[bransjenynorsk] => Internett design og programmering
)
)
)
)
[dummy] =>
)
The PHP code is the following:
$json = utf8_encode(file_get_contents($url, 'UTF-8'));
$data = json_decode($json);
print_r($data->result);
I have tried echo $data->etternavn;
I know this might be a simple question, sorry. I'm not good with coding.
You can do this:
<?php
$json = utf8_encode(file_get_contents($url, 'UTF-8'));
$data = json_decode($json, true);
print_r($data['result'][1]['listing']['duplicates'][0]['etternavn']);
?>
You have to traverse through this complex structure. To get etternavn you need to do this:
$data = json_decode($json);
echo $data->result->{1}->listing->duplicates->{0}->etternavn;
Or as suggested in comments, pass next parameter of json_decode to true. Which will convert it into array.
$data = json_decode($json, true);
echo $data['result'][1]['listing']['duplicates'][0]['etternavn'];

Extracting a property from an array of an array of objects

I've got an object, containing an array of objects, containing an array of values:
stdClass Object (
[devices] => Array (
[0] => stdClass Object (
[location] => 1
[delegate] =>
[type] => 1
[id] => 1234
[IP] => 1.2.3.4
[name] => host1
[owner] => user6
[security] => 15
)
[1] => stdClass Object (
[location] => 2
[delegate] =>
[type] => 1
[id] => 4321
[IP] => 4.3.2.1
[name] => host2
[owner] => user9
[security] => 15
)
)
)
I want to extract just the id and name into an array in the form of:
$devices['id'] = $name;
I considered using the array_map() function, but couldn't work out how to use it... Any ideas?
This will generate you a new array like I think you want
I know you says that delegate is an object but the print does not show it that way
$new = array();
foreach($obj->devices as $device) {
$new[][$device->id] = $device->name;
}
Would something like this not work? Untested but it cycles through the object structure to extract what I think you need.
$devices = myfunction($my_object);
function myfunction($ob){
$devices = array();
if(isset($ob->devices)){
foreach($ob->devices as $d){
if(isset($d->delegate->name && isset($d->delegate->id))){
$devices[$d->delegate->id] = $d->delegate->name;
}
}
}
return($devices);
}
Im usually using this function to generate all child and parent array stdclass / object, but still make key same :
function GenNewArr($arr=array()){
$newarr = array();
foreach($arr as $a=>$b){
$newarr[$a] = is_object($b) || is_array($b) ? GenNewArr($b) : $b ;
}
return $newarr;
}

Cycling an array and delete item

I need help :)
I've to code a script that, cycling through an array inside an array , delete an element if in XXX field there isn't value (is NULL ).
My array is:
Array (
[idCampaign] => 3
[idIT] => 322
[recipients] =>Array (
[0] => stdClass Object ( [name] => minnie [email] => blabla#gmail.com [XXX] => )
[1] => stdClass Object ( [name] => [email] => fddd#gmail.it [XXX] => 0.88451100 )
) ) [date] => MongoDate Object ( [sec] => 1468503103 [usec] => 0 ) )
In this example the item [0] has no value in XXX value so my output array will be:
Array (
[idCampaign] => 3
[idIT] => 322
[recipients] =>Array (
[1] => stdClass Object ( [name] => [email] => fddd#gmail.it [XXX] => 0.88451100 )
) ) [date] => MongoDate Object ( [sec] => 1468503103 [usec] => 0 ) )
i hope that you can help me :)
You could use a nested foreach() Loop to cycle through the Data and then perform some tests, which on failing, guarantees that it is safe to unset the pertinent variable. Here's how:
<?php
// WE SIMULATE SOME DATA TO POPULATE THE ARRAY, ONLY FOR TESTING PURPOSES
$objDate = new stdClass();
$objRez1 = new stdClass();
$objRez2 = new stdClass();
$objRez1->name = "minnie";
$objRez1->email = "blabla#gmail.com";
$objRez1->XXX = null;
$objRez2->name = null;
$objRez2->email = "fddd#gmail.it";
$objRez2->XXX = 0.88451100;
$objDate->sec = 1468503103;
$objDate->usec = 0;
// IN THE END WE NOW HAVE A SAMPLE ARRAY (SIMULATED) TO WORK WITH.
$arrData = array(
'idCampaign' => 3,
'idIT' => 322,
'recipients' => array(
$objRez1,
$objRez2
),
'date' =>$objDate,
);
// LOOP THROUGH THE ARRAY OF DATA THAT YOU HAVE
// NOTICE THE &$data IN THE LOOP CONSTRUCT...
// THIS IS NECESSARY FOR REFERENCING WHEN WE UNSET VARIABLES WITHIN THE LOOP
foreach($arrData as $key=>&$data){
// SINCE THE XXX KEY IS STORED IN THE 'recipients' ARRAY,
// WE CHECK IF THE CURRENT KEY IS 'recipients' & THAT $data IS AN ARRAY
if($key == "recipients" && is_array($data)){
// NOW WE LOOP THROUGH THE DATA WHEREIN THE 'XXX' KEY LIVES
foreach($data as $obj){
// IF THE VALUE OF THE XXX KEY IS NULL OR NOT SET,
// WE SIMPLY UNSET IT...
if(!$obj->XXX){
unset($obj->XXX);
}
}
}
}
var_dump($arrData);
You can verify the Results HERE.
Hope this could offer you a little tip on how to implement it rightly on your own...
This should do the job
foreach($arrayOfObjects as $index => $object){
if(!isset($object->xxx) || empty($object->xxx)){
unset($arrayOfObjects[$index]);
}
}

Convert Stripe API response to JSON using stripe-php library

I'm accessing customer data from the Stripe API, which I'd like to convert to JSON. Usually I'd convert an object to an array and use json_encode() but I don't seem able to in this case, even when trying to access the nested arrays.
This is the response I'm trying to convert to json:
Stripe_Customer Object
(
[_apiKey:protected] => MY_KEY_IS_HERE
[_values:protected] => Array
(
[id] => cus_2dVcTSc6ZtHQcv
[object] => customer
[created] => 1380101320
[livemode] =>
[description] => Bristol : John Doe
[email] => someone6#gmail.com
[delinquent] =>
[metadata] => Array
(
)
[subscription] =>
[discount] =>
[account_balance] => 0
[cards] => Stripe_List Object
(
[_apiKey:protected] => MY_KEY_IS_HERE
[_values:protected] => Array
(
[object] => list
[count] => 1
[url] => /v1/customers/cus_2dVcTSc6ZtHQcv/cards
[data] => Array
(
[0] => Stripe_Object Object
(
[_apiKey:protected] => MY_KEY_IS_HERE
[_values:protected] => Array
(
[id] => card_2dVcLabLlKkOys
[object] => card
[last4] => 4242
[type] => Visa
[exp_month] => 5
[exp_year] => 2014
[fingerprint] => NzDd6OkHnfElGUif
[customer] => cus_2dVcTSc6ZtHQcv
[country] => US
[name] => John Doe
[address_line1] =>
[address_line2] =>
[address_city] =>
[address_state] =>
[address_zip] =>
[address_country] =>
[cvc_check] => pass
[address_line1_check] =>
[address_zip_check] =>
)
[_unsavedValues:protected] => Stripe_Util_Set Object
(
[_elts:Stripe_Util_Set:private] => Array
(
)
)
[_transientValues:protected] => Stripe_Util_Set Object
(
[_elts:Stripe_Util_Set:private] => Array
(
)
)
[_retrieveOptions:protected] => Array
(
)
)
)
)
[_unsavedValues:protected] => Stripe_Util_Set Object
(
[_elts:Stripe_Util_Set:private] => Array
(
)
)
[_transientValues:protected] => Stripe_Util_Set Object
(
[_elts:Stripe_Util_Set:private] => Array
(
)
)
[_retrieveOptions:protected] => Array
(
)
)
[default_card] => card_2dVcLabLlKkOys
)
[_unsavedValues:protected] => Stripe_Util_Set Object
(
[_elts:Stripe_Util_Set:private] => Array
(
)
)
[_transientValues:protected] => Stripe_Util_Set Object
(
[_elts:Stripe_Util_Set:private] => Array
(
)
)
[_retrieveOptions:protected] => Array
(
)
)
Any help greatly appreciated!
PHP has reserved all method names with a double underscore prefix for future use. See https://www.php.net/manual/en/language.oop5.magic.php
Currently, in the latest php-stripe library, you can convert the Stripe Object to JSON by simpl calling **->toJSON().
[PREVIOUSLY]
All objects created by the Stripe PHP API library can be converted to JSON with their __toJSON() methods.
Stripe::setApiKey("sk_xxxxxxxxxxxxxxxxxxxxxxxxx");
$customer = Stripe_Customer::create(array(
"card" => $token,
"plan" => $plan,
));
$customer_json = $customer->__toJSON();
There is also a __toArray($recursive=false) method. Remember to set true as argument otherwise you will get an array filled with stripe objects.
Stripe::setApiKey("sk_xxxxxxxxxxxxxxxxxxxxxxxxx");
$customer = Stripe_Customer::create(array(
"card" => $token,
"plan" => $plan,
));
$customer_array = $customer->__toArray(true);
The attributes of Stripe_Objects can be accessed like this:
$customer->attribute;
So to get the customer's card's last4, you can do this:
$customer->default_card->last4;
However, you'll need to make sure you have the default_card attribute populated. You can retrieve the default_card object at the same time as the rest of the customer by passing the expand argument:
$customer = Stripe_Customer::retrieve(array(
"id" => "cus_2dVcTSc6ZtHQcv",
"expand" => array("default_card")
));
On the latest version, You can use echo $customer->toJSON(); to get the output as JSON.
I have done this way
`Stripe::setApiKey("sk_xxxxxxxxxxxxxxxxxxxxxxxxx");
$stripe_response= Stripe_Customer::create(array(
"card" => $token,
"plan" => $plan,
));
//Encoding stripe response to json
$resposnse_json_ecoded= json_encode($stripe_response);
//decoding ecoded respose
$response_decoded = json_decode($resposnse_json_ecoded, true);
//get data in first level
$account_id=$response_decoded['id'];
$individual = $response_decoded['individual'];
//get data in second level
$person_id=$individual['id'];`
If, like me, you arrived here looking for the python 2.7 solution, simply cast the stripe_object to str(). This triggers the object's inner __str__() function which converts the object into a JSON string.
E.g.
charge = stripe.Charge....
print str(charge)
Your top level object contains other object instances - the cast to (array) affects only the top level element. You might need to recursively walk down - but I'd do it differently here given that the classes are serializable:
$transfer = serialize($myobject);
What are you going to do with the otherwise JSONified data?
If you're going to transfer an object without the class information you might try to use Reflection:
abstract class Object {
/**
* initialize an object from matching properties of another object
*/
protected function cloneInstance($obj) {
if (is_object($obj)) {
$srfl = new ReflectionObject($obj);
$drfl = new ReflectionObject($this);
$sprops = $srfl->getProperties();
foreach ($sprops as $sprop) {
$sprop->setAccessible(true);
$name = $sprop->getName();
if ($drfl->hasProperty($name)) {
$value = $sprop->getValue($obj);
$propDest = $drfl->getProperty($name);
$propDest->setAccessible(true);
$propDest->setValue($this,$value);
}
}
}
else
Log::error('Request to clone instance %s failed - parameter is not an object', array(get_class($this)));
return $this;
}
public function stdClass() {
$trg = (object)array();
$srfl = new ReflectionObject($this);
$sprops = $srfl->getProperties();
foreach ($sprops as $sprop) {
if (!$sprop->isStatic()) {
$sprop->setAccessible(true);
$name = $sprop->getName();
$value = $sprop->getValue($this);
$trg->$name = $value;
}
}
return $trg;
}
}
This is the base class of most of my transferrable classes. It creates a stdClass object from a class, or initializes a class from a stdClass object. You might easily adopt this to your own needs (e.g. create an array).
This is already in a JSON format so you do need to convert it again into json_encode()
just pass it into your script

Problem With SimpleXML Parsing WoWArmory attributes

This is an example item:
SimpleXMLElement Object
(
[#attributes] => Array
(
[displayInfoId] => 62116
[durability] => 100
[gem0Id] => 41401
[gem1Id] => 40123
[gem2Id] => 0
[gemIcon0] => inv_jewelcrafting_shadowspirit_02
[gemIcon1] => inv_jewelcrafting_gem_37
[icon] => inv_helmet_98
[id] => 48592
[level] => 245
[maxDurability] => 100
[name] => Liadrin's Headpiece of Triumph
[permanentEnchantIcon] => ability_warrior_shieldmastery
[permanentEnchantItemId] => 44876
[permanentenchant] => 3819
[pickUp] => PickUpLargeChain
[putDown] => PutDownLArgeChain
[randomPropertiesId] => 0
[rarity] => 4
[seed] => 0
[slot] => 0
)
)
I'm trying to get a JSON object with each item, but there's about 17 or something, and if I try to json_encode() it's giving me "#attributes" as an object containing all the stuff I want. Help?
Something like this:
<?php
$sxm = new SimpleXMLElement("<a name=\"kkk\" other=\"foo\"/>");
$attrs = $sxm->attributes();
var_dump(json_encode(reset($attrs)));
gives:
string(28) "{"name":"kkk","other":"foo"}"
The problem you were experiencing was because $xmlObj->attributes() returns a SimpleXMLElement that, when converted as an array, is an array with the key "#attributes" and a value with an array that actually has the attributes as (name => value) pairs.
How about this
$jsonArray = array();
foreach ($xmlObj->attributes() as $attr => $value) {
$jsonArray[$attr] = (string)$value;
}
$jsonString = json_encode($jsonArray);
Edit: You may also be able to simply use
$jsonString = json_encode($xmlObj->attributes());
however I'm not sure if the attribute values are returned as strings or objects (edit - turns out you can't. See Artefacto's solution).
How about this?
$array = (array)$simplexml->node->attributes();
$jsonArray = json_encode($array['#attributes']);

Categories