Echo specific item from array [duplicate] - php

This question already has answers here:
How can I access an array/object?
(6 answers)
Closed 5 years ago.
I want to echo value from this array, so it'll say "true"
::object(stdClass)#25 (2) { ["Name"]=> string(3) "DPV" ["Value"]=> string(4) "true" }
How can I do this in PHP?

assuming the object property of Value is public ( which it is or it wouldn't be output ) you can use PHP's object operator ->
Such as:
echo $obj->Value;
In the case that it isn't public, you would want to use a get menthod, such as this
class obj{
protected $Value = true;
public function getValue(){
return $this->Value;
}
}
$obj = new obj();
echo $obj->getValue();
AS you can see both access the objects property the same basic way ( using the -> ). Which is different then how you access elements in an array. You can implement ArrayAccess on an object, which allows you to use it as if it was an array, but that's a post for another time.
http://php.net/manual/en/class.arrayaccess.php

Simply
<?php
echo $objectVarName->Value;
Note: $objectVarName is not an array, it is an object.
A very common example of arrays in PHP as following:
$array = array(
"foo" => "bar",
"bar" => "foo",
);

Here is simple solution, might be helpful.
<?php
//Let suppose you have this array
$arr = array('id'=>1,'name'=>'alax','status'=>'true');
//Check out array (Basically return array with key and value).
print_r($arr);
// Get value from the particular index
echo "<br/>Your value is:".$arr['status'];
?>

Related

Show concrete data of array with objects [duplicate]

This question already has answers here:
Fatal error: Cannot use object of type User as array
(1 answer)
PHP Error: Cannot use object of type stdClass as array (array and object issues) [duplicate]
(6 answers)
How can I access an array/object?
(6 answers)
Closed 4 years ago.
I want to show a specific data of an array, I have the following code and I am trying to print the printConcreteStudent function to print a specific student that I indicate passed through the variable $name.
When trying to find the student I get the following error:
Fatal error: Uncaught Error: Can not use object of type Student as
array
The structure of the array is as follows:
array(1) {
[0]=>
object(Student)#1 (4) {
["name"]=>
string(5) "Student1"
["lastname":"Student":private]=>
string(7) "lastName1"
}
}
And the function with which I am trying to print a specific data :
function printConcreteStudent($name) {
foreach($this->students as $key=>$value){
if($value["name"] == $name){
echo $value->getName() . " ";
echo $value->getLastName() . " ";
}
}
}
As you error state you can use object as array. In $this->students every object is of type object(Student) so you can access the name field by using "key" index. You need to change: if($value["name"] == $name){ (because cannot use $value["name"] as $value is object) to:
if($value->getName() == $name){
students is array of object so value is an object so $value->name; is how you will access the name attribute
foreach($this->students as $key=>$value){
if($name==$value->name){
//print the attributes...
}
}
It's better to lower case both of the values and then compare so that it may find the result even if capital letters are entered as input

Print PHP array of objects in jQuery [duplicate]

This question already has answers here:
Serializing PHP object to JSON
(11 answers)
Closed 4 years ago.
The array below could return in various ways (with more or less elements):
array(4) { ["imagen"]=> string(11) "bánner.jpg" ["alt"]=> string(5) "muaka" ["destino"]=> string(7) "op_tipo" ["tipo"]=> string(13) "obj_connected" }
array(3) { ["imagen"]=> string(12) "Logo_RGB.jpg" ["alt"]=> string(7) "test123" ["destino"]=> string(11) "op_list_gen" }
Im saving this in a variable in PHP called: $filtrosBanner;. How can I get the values from this in jQuery?
I have saved the variable in jQuery as follows:
var opDestino = "<?php echo $filtrosBanner; ?>";
This returns an array but im not sure how to access each value individually.
The most simple approach for your task would be:
var opDestino = <?php echo json_encode($filtrosBanner); ?>;
This way you are converting an object (or array) from PHP to Javascript syntax.
I would use json_encode(). This should create a json object for your var opDestino.
Like so:
var opDestino = <?php echo json_encode($filtrosBanner); ?>;
You need to implode your array as string using your PHP code and save it in a php variable as
PHP
$myarray=implode(',',$array);
Now take it in a variable in your script and then explode it using , to get your final array as
JQUERY
var myarray='<?php echo $myarray;?>';
var originalarray=myarray.split(',');
Note: but it will work for only indexed array, not associative array
Return the array with json_encode in PHP.
return json_encode($filtrosBanner);
In Javascript/jQuery use
var obj = JSON.parse(<?php echo $filtrosBanner?>);
To use this object , use it like this.
obj.propertyname

how do i grab orderId from this array? [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
How can i enter this array and grab the orderId ?
array(1) {
["data"] => array(1) {
["orderId"] => int(100)
}
}
ive tried to
print_r ["array"]["1"]["array"]["1"]["orderId"];
ive tried
foreach($array as $data)
echo ["data"]["orderId"] ;
Also note, i am receiving this json as a webhook and decoding it to php object with json_decode($json, true);
What am i missing? Should be simple but i cannot get it.
Thanks
Assuming the JSON data you're receiving is in the $array variable:
$orderId = $array["data"]["orderId"];
Explanation:
First you grab the "data" property from the array
That data property contains another array which has its own properties.
From that array, you can grab the "orderId" property.
I hope this helps :)
If your array is named $that, use $that['data']['orderId'];
Try this $array["data"]["orderId"] `

How to get object(stdClass) value in php? [duplicate]

This question already has answers here:
How to access object properties with names like integers or invalid property names?
(7 answers)
Closed 6 years ago.
I have some object like this :
object(stdClass)#188 (1) { ["0"]=> string(1) "1" }
How could I print that object value in php ?
Thank you.
Try this, Best way for single value
echo $objects->{"0"};
and for multiple values
foreach($objects as $val )
{
echo $val;
}
Very short answer
var_dump($obj->{'0'});
You have access to the internal content of the Object via: ->{"0"}. Assuming you want to use the variable or echo it out for some reasons, you can simply do:
<?php echo $object->{"0"}; ?>

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