Access Object Value - php

I am trying to pull out a value from inside a larger object. The main object from an xml file via SimpleXML.
When I var_dump($data->extensions->runTime); this section of the object I get:
object(SimpleXMLElement)#21 (1) {
[0]=>
string(8) "2852.462"
}
How can I access that 2852.462??
I have tried everything I can think of, via array [0], even with a foreach statement. I can't figure out how to access only the value.

Cast it to string:
$value = (string)$data->extensions->runTime[0];
Or better to float:
$value = (float)$data->extensions->runTime[0];

Related

Can't use JSON array in a php loop

i have a json file, that has to be parsed in a loop.
i cant seem to succeed
JSON:
{"IMD":{"url":"http:\/\/www.google.com","timeOut":1515155361},"cvH":{"url":"http:\/\/www.google.com","timeOut":1515155364}}
PHP:
<?php
$linkyValues="./linky.json";
if (file_exists($linkyValues)) {
$fileStream = fopen($linkyValues, 'r');
$fileValue=json_decode(fread($fileStream, filesize($linkyValues)));
fclose($fileStream);
echo count($fileValue);//Always 1!
for($i=0;$i<count($fileValue);$i++){
$timeout=$fileValue->item($i)->timeOut;
if(time()>=$timeout){
unset($fileValue[$i]);
}
}
$fileStream = fopen($linkyValues, 'w');
fwrite($fileStream, json_encode($fileValue));
fclose($fileStream);
}
?>
my problem is that count($fileValue) is always 1.
Output of var_dump($fileValue):
object(stdClass)#2 (2) {
["IMD"]=>
object(stdClass)#1 (2) {
["url"]=>
string(21) "http://www.google.com"
["timeOut"]=>
int(1515155361)
}
["cvH"]=>
object(stdClass)#3 (2) {
["url"]=>
string(21) "http://www.google.com"
["timeOut"]=>
int(1515155364)
}
}
it looks like an array to me...
JSON does not support the concept of an associative array, but stores such maps as objects instead.
Your JSON file contains such an object. For PHP this means, that it can either import it as an stdClass ( object ) or as an associatiave array.
This is decided by the json_decode's second parameter, that is either TRUE to read the object as an associative array, or FALSE to read it as an object.
Therefore this will fix your problem:
$fileValue = json_decode(fread($fileStream, filesize($linkyValues)), TRUE);
json_decode documentation
In addition to that, your code has problems with iterating the array. You use $fileValue->item($i) as well as $fileValue[$i], while you have an associative array.
You work with it as if it was an indexed array, while it is an associative array, which means it has keys instead of indices, that identify the values in your array.
The propper way to iterate an associative array is with foreach, like deomstrated belo:
foreach($fileValue as $key => $value) {
if (time() >= $value['timeOut']) {
unset($fileValue[$key]);
}
}
Yet, since you only want to remove specific values, you can use array_filter as well:
$fileValue = array_filter($fileValue, function($value){
return time() < $value['timeOut'];
});
array_filter will then take care of removing the specified fields from your array, so you do not have to unset them manually.
You can use :
count((array)$fileValue);
You're mixing up arrays and objects here.
count() can only be used on arrays, however you can cast an object to array to achieve the same thing.
$fileValue[$i] is a method to access an array, which won't work with your json object.
I see a solution already is to just change your object to an array so I'd like to offer the solution if you wanted to stick with objects.
$linkyValues="./linky.json";
if (file_exists($linkyValues)) {
$fileStream = fopen($linkyValues, 'r');
$fileValue=json_decode($jsonString);
fclose($fileStream);
//Cast the object to an array to get the count, but count isn't really requierd
echo count((array)$fileValue);
//loop through the object
foreach($fileValue as $key=>$fv){
//pull the timeout
$timeout=$fv->timeOut;
//do the check
if(time()>=$timeout){
//remove the timeout from the object
unset($fileValue->$key);
}
}
$fileStream = fopen($linkyValues, 'w');
fwrite($fileStream, json_encode($fileValue));
fclose($fileStream);
}
?>

Saving form values to an Object as attributes (Associative Array, PHP, PDO, lunk head)

I'm working on an AJAX CRUD and I cannot get the form values in the Assoc. array to save individually as object attributes for the MySQL query.
I am following enter link description here but instead of the mysqli I'm using PDO.
Not much of a php person and this is my first OOP use of PDO and JSON.
The vardump() shows the input text is there...
// get posted data
$data = json_decode(file_get_contents("php://input"), true);
// set event property values
$event=>mainTitle = $data->main-title;
$event->subTitle = $data->sub-title;
$event->eventUrl = $data->event-url;
And the dumps:
array(9) {
["main-title"]=>
string(15) "Test Main Title"
["sub-title"]=>
string(14) "Test Sub title"
["event-url"]=>
string(9) "Test URTL"
...
object(Event)#3 (11) {
["conn":"Event":private]=>
object(PDO)#2 (0) {
}
["table_name":"Event":private]=>
string(8) "tblEvent"
["mainTitle"]=>
int(0)
["subTitle"]=>
int(0)
["eventUrl"]=>
int(0)
...
try changing $event=>mainTitle to $event->mainTitle
You have passed a second argument to json_decode() what means you'd like to get an array instead of the object. So just work like with the array. Replace to $event->mainTitle = $data['main-title'];
I found the answer for part of my problem here: Handling-JSON-like-a-boss-in-PHP
json_decode() is able to return both an object or associative array.
//For an object:
$result = json_decode($string);
//For an Assoc. Array:
$result = json_decode($string, true);
What I struggled with is that the var_dump() returns almost exact result for the two. They indeed have to be the same type.
The second part of my problem that was more subvert was having hyphens in the object attribute names. I didn't find a reason why but for sake of clarity in my code I just removed them.

trying to get an element from an array in php

i have an array after convert it from xml data and i have var_dump the data in array like :
object(SimpleXMLElement)#651 (1) {
["authenticationSuccess"]=>
object(SimpleXMLElement)#652 (1) {
["user"]=>
string(9) "yassine"
}
}
i want to get the value the attribut user that equal "yassine" in this cas .
i trying
$xml["authenticationSuccess"]["user"]
but not working , it return null value , is there any solution to get this data from the array .
some help please
It seems your variable is not array but object, so you need to use $xml->authenticationSuccess->user;
As the var_dump says, you have an object instead of an associative array. You can access object fields like this:
$xml->authenticationSuccess->user;
or this:
$xml->{"authenticationSuccess"}->{"user"};

Accessing a specific object by name/number?

I'm returning some data, and testing my return by using var_dump($this);. It returns the following:
object(ReportingService)#333 (2) {
["_arrErrors"]=>
array(0) {
}
["nameWS"]=>
string(14) "reportingstuff"
}
{"arrMessages":[{"_strMessage":"Example.","_strType":"valid","_strModule":null}],"arrContent":{"isSuccess":"1","statistics":"<div id=\"entities\">
What I am trying to do is to access the nameWS property of the object, but cannot seem to do so.
What I've tried:
var_dump($this[0]->nameWS);
Use the following:
$this->nameWS;
You find more information in the manual Setting and Getting Object Properties
You can access it via:
$this->nameWS;
The zero you were using is for the array in "_arrErrors", so you don't need that.
echo $this->nameWS;
will output:
reportingstuff

Undefined offset while accessing array element which exists

I have an array and PHP and when I print it out I can see the values I need to access, but when I try accessing them by their key I am getting a PHP Notice. I printed the array with print_r:
Array
(
[207] => sdf
[210] => sdf
)
When I try to access the array using the index I get an undefined offset notice. Here is my code:
print_r($output);
echo $output[207]; // Undefined Offset
echo $output["207"]; // Undefined Offset
The $output array is the result of a call to array_diff_key and is input originally as JSON through an HTTP POST request.
array_keys gives me the following:
Array
(
[0] => 207
[1] => 210
)
In response to the comments:
var_dump(key($output)); outputs:
string(3) "207"
var_dump(isset($output[key($output)])); outputs:
bool(false)
See this section on converting an object to an array in the PHP Manual:
The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name.
When converting to an array from an object in PHP, integer array keys are stored internally as strings. When you access array elements in PHP or use an array normally, keys that contain valid integers will be converted to integers automatically. An integer stored internally as a string is an inaccessible key.
Note the difference:
$x = (array)json_decode('{"207":"test"}');
var_dump(key($x)); // string(3) "207"
var_dump($x);
// array(1) {
// ["207"]=>
// string(4) "test"
// }
$y['207'] = 'test';
var_dump(key($y)); // int(207)
var_dump($y);
// array(1) {
// [207]=>
// string(4) "test"
// }
print_r on both those arrays gives identical output, but with var_dump you can see the differences.
Here is some code that reproduces your exact problem:
$output = (array)json_decode('{"207":"sdf","210":"sdf"}');
print_r($output);
echo $output[207];
echo $output["207"];
And the simple fix is to pass in true to json_decode for the optional assoc argument, to specify that you want an array not an object:
$output = json_decode('{"207":"sdf","210":"sdf"}', true);
print_r($output);
echo $output[207];
echo $output["207"];
The problem arises when casting to array an object that has string keys that are valid integers.
If you have this object:
object(stdClass)#1 (2) {
["207"]=>
string(3) "sdf"
["210"]=>
string(3) "sdf"
}
and you cast it with
$array = (array)$object
you get this array
array(2) {
["207"]=>
string(3) "sdf"
["210"]=>
string(3) "sdf"
}
which has keys that can only be accessed by looping through them, since a direct access like $array["207"] will always be converted to $array[207], which does not exist.
Since you are getting an object like the one above from json_decode() applied to a string like
$json = '{"207":"sdf", "210":"sdf"}'
The best solution would be to avoid numeric keys in the first place. These are probably better modelled as numeric properties of an array of objects:
$json = '[{"numAttr":207, "strAttr":"sdf"}, {"numAttr":210, "strAttr":"sdf"}]'
This data structure has several advantages over the present one:
it better reflects the original data, as a collection of objects
which have a numeric property
it is readily extensible with other properties
it is more portable across different systems
(as you see, your current data structure is causing issues in PHP, but if you
should happen to use another language you may easily encounter
similar issues).
If a property → object map is needed, it can be quickly obtained, e.g., like this:
function getNumAttr($obj) { return $obj->numAttr; } // for backward compatibility
$arr = json_decode($json); // where $json = '[{"numAttr":...
$map = array_combine(array_map('getNumAttr', $arr), $arr);
The other solution would be to do as ascii-lime suggested: force json_decode() to output associative arrays instead of objects, by setting its second parameter to true:
$map = json_decode($json, true);
For your input data this produces directly
array(2) {
[207]=>
string(3) "sdf"
[210]=>
string(3) "sdf"
}
Note that the keys of the array are now integers instead of strings.
I would consider changing the JSON data structure a much cleaner solution, though, although I understand that it might not be possible to do so.
I've just found this bug which causes array elements to be inaccessible sometimes in PHP when the array is created by a call to unserialize.
Create a test PHP file containing (or run from the command line) the following script:
<?php
$a = unserialize('a:2:{s:2:"10";i:1;s:2:"01";i:2;}');
print $a['10']."\n";
$a['10'] = 3;
$a['01'] = 4;
print_r($a);
foreach ($a as $k => $v)
{
print 'KEY: ';
var_dump($k);
print 'VAL: ';
var_dump($v);
print "\n";
}
If you get errors you have a version of PHP with this bug in it and I recommend upgrading to PHP 5.3
Try
var_dump($output);
foreach ($output as $key => val) {
var_dump($key);
var_dump($val);
}
to learn more on what is happening.
What exact line/statement is throwing you a warning?
How did you print the array? I would suggest print_r($arrayName);
Next, you can print individual elements like: echo $arrayName[0];
Try use my approach:
class ObjectToArray {
public static function convert( $object ) {
if( !is_object( $object ) && !is_array( $object ) ) {
return $object;
}
if( is_object( $object ) ) {
$object = get_object_vars( $object );
}
return array_map( 'ObjectToArray::convert', $object );
}
}
$aNewArray = ObjectToArray::convert($oYourObject);
Just put error_reporting(0); in you method or at start of file. It will solved your issue.

Categories