Fetching an object in Mongo PHP library - php

I use this MongoDB library for PHP
If I use this code:
$db->users->find();
I get an associative array.
Is it possible to get an object as a result of find() method?
For example, in PDO I can do it like this:
$stmt->fetch(PDO::FETCH_OBJ);
Thank you.

If all you're looking for is an stdclass object (like with PDO::FETCH_OBJ), you can cast the current element:
$obj = (object) $db->users->find()->getNext();
Learn more about casting in the PHP manual:
Type Juggling (PHP Manual)

The call
$db->users->find();
returns a \MongoCursor object, which is an iterator you can loop over in a foreach loop as you would with an array. But each result you get from it, though, is an associative array.
http://php.net/mongocollection.find
So, to get objects instead you could cast each item to object prior to using it :
$list = $db->users->find();
foreach($list as $user) {
$user = (object)$user; // object cast here
echo $user->name; // use it as an object
}

Related

How to convert an object properties into an array in php

Those data in $data variable. When I'm using dd($data); I got this:
CurlHandle {#1918 ▼
+url: "https://example.com"
+content_type: "application/json; charset=UTF-8"
+http_code: 200
+header_size: 887
+namelookup_time_us: 139522
+pretransfer_time_us: 326662
+redirect_time_us: 0
+starttransfer_time_us: 668686
+total_time_us: 668752
}
I want to convert this data to an array.
I'm using this: $arr = json_decode($data,true);
But, this is not working. Now, how can I convert this?
You can use below solution
$yourArray = json_decode(json_encode($yourObject), true);
and this convert object to an array for more info
Objects are, in PHP, maybe iterable. Notice, you may iterate through an object's public fields only via the foreach loop. So the following works:
$array = [];
foreach ($object as $property) {
$array[] = $property; // Stores public field only
}
var_dump($array);
Simply to get an array of object properties, you may use the get_object_vars() function.
var_dump(get_object_vars($object));
You may cast an object to be an array as #MoussabKbeisy said. And this would be the easiest way:
$array = (array) $object;
Here is another way is using ArrayIterator:
$iterator = new ArrayIterator($object);
var_dump(iterator_to_array($iterator));
while this is a PHP Object so you can deal with it by 2 ways:
1- if you want to get on of it's parameters, you can simply use
$yourObject->parameter;
2- if you need to use convert and use it as array, then there is different ways to convert an object to an array in PHP
//1
$array = (array) $yourObject;
//2
$array = json_decode(json_encode($yourObject), true);
Also see this in-depth blog post:
Fast PHP Object to Array conversion

Why this variable act as a object?

I am very new in programming world. It may it's a very silly question. But I need a clear concept about this issue that's why I am asking this question.
<?php
$json = '{"a":1}';
$data = json_decode($json);
echo $data->a;
?>
I have learn when we called a object that should be
$data = new json_decode($json);
Why this $data worked as a object without new ?
That is a json array, it can be converted to an object or to an associative array.
If you use the function
$object = json_decode($array);
the destination variable will be treated as an object.
If your will is just to decode to a json array to an associative array you have to add a true after the array
$assArray= json_decode($array,true);
In this case you can access the values as a normal array
echo($assArray["a"]);
Will output 1.
However I suggest you to check the official manual, is very clear in the explanation of these function
PHP Official manual json_decode
You need to store it inside a variable to use like an array.
<?php
$json = '{"a":1}';
$data = json_decode($json,true);
echo $data['a'];
?>
By default json_decode (without providing second parameter) will return you object, which means that the function itself will create (and return) new stdClass for you.
If you want array instead:
$data = json_decode($json, true);
It's because you use a function that returning an instance.
When you use new operator, you create an instance explicitely from className. With examples :
function return_instance() {
return new ClassName();
}
$obj1 = return_instance();
$obj2 = new ClassName();
// The two objects return the same type of object
json_decode by default attempts to return an object rather than an array. In doing so you don't need to new json_decode, rather just call the function directly. You can return an array by adding a second parameter true.
For example:
$asObject = json_decode($jsonText);
$asArray = json_decode($jsonText, true);
The new keyword essentially invokes a class's constructor to create a new object. If you like, you can think of json_decode as calling new inside the function so to create a new object for you.
becouse json_deocde return type is of object type here is example
function jsonDecode($json){
//here logic of decoding;
return new stdClass();
}
now it will type of object

Fetching all rows as Object with pdo php

I know that the function fetchObject (http://www.php.net/manual/en/pdostatement.fetchobject.php) gives me the next row as an object of the specified class, but I want to get all the rows as an object of the specified class, does PDO has some function to this or I have to do it manually???
THanks!!
You are looking for PDOStatement::fetchAll:
PDOStatement::fetchAll — Returns an array containing all of the result set rows
Example usage:
$arr = $stmt->fetchAll(PDO::FETCH_CLASS, $class_name, $constructor_args);
If you do not need all of the objects in a single array, you will probably find iterating through all the rows to work just as well:
while ($obj = $stmt->fetchObject($class_name, $constructor_args)) {
// Process $obj
}

How to decode the following code in Json?

I'm trying to decode the following JSON using php json_decode function.
[{"total_count":17}]
I think the square brackets in output is preventing it. How do I get around that? I can't control the output because it is coming from Facebook FQL query:
https://api.facebook.com/method/fql.query?format=json&query=SELECT%20total_count%20FROM%20link_stat%20WHERE%20url=%22http://www.apple.com%22
PHP's json_decode returns an instance of stdClass by default.
For you, it's probably easier to deal with array. You can force PHP to return arrays, as a second parameter to json_decode:
$var = json_decode('[{"total_count":17}]', true);
After that, you can access the variable as $result[0]['total_count']
See this JS fiddle for an example of how to read it:
http://jsfiddle.net/8V4qP/1
It's basically the same code for PHP, except you need to pass true as your second argument to json_decode to tell php you want to use it as associative arrays instead of actual objects:
<?php
$result = json_decode('[{"total_count":17}]', true);
print $result[0]['total_count'];
?>
if you don't pass true, you would have to access it like this: $result[0]->total_count because it is an array containing an object, not an array containing an array.
$json = "[{\"total_count\":17}]";
$arr = Jason_decode($json);
foreach ($arr as $obj) {
echo $obj->total_count . "<br>";
}
Or use json_decode($json, true) if you want associative arrays instead of objects.

Does PHP feature short hand syntax for objects?

In javascript you can easily create objects and Arrays like so:
var aObject = { foo:'bla', bar:2 };
var anArray = ['foo', 'bar', 2];
Are similar things possible in PHP?
I know that you can easily create an array using the array function, that hardly is more work then the javascript syntax, but is there a similar syntax for creating objects? Or should I just use associative arrays?
$anArray = array('foo', 'bar', 2);
$anObjectLikeAssociativeArray = array('foo'=>'bla',
'bar'=>2);
So to summarize:
Does PHP have javascript like object creation or should I just use associative arrays?
For simple objects, you can use the associative array syntax and casting to get an object:
<?php
$obj = (object)array('foo' => 'bar');
echo $obj->foo; // yields "bar"
But looking at that you can easily see how useless it is (you would just leave it as an associative array if your structure was that simple).
There was a proposal to implement this array syntax. But it was declined.
Update    The shortened syntax for arrays has been rediscussed, accepted, and is now on the way be released with PHP 5.4.
But there still is no shorthand for objects. You will probably need to explicitly cast to object:
$obj = (object) ['foo'=>'bla', 'bar'=>2];
As of PHP 5.4, you can do this:
$array = ['foo'=>'bla', 'bar'=>2];
It's not much shorter, but you'll appreciate it if you need to use a lot of hard coded nested arrays (which isn't altogether uncommon).
If you want an object, you would still need to cast each array:
$object = (object) ['foo'=>'bla', 'bar'=>2];
According to the new PHP syntaxes,
You can use
$array = [1,2,3];
And for associative arrays
$array = ['name'=>'Sanket','age'=>22];
For objects you can typecast the array to object
$object = (object)['name'=>'Sanket','age'=>22];
There is no object shorthand in PHP, but you can use Javascript's exact syntax, provided you use the json_encode and json_decode functions.
The method provided by crescentfresh works very well but I had a problem appending more properties to the object. to get around this problem I implemented the spl ArrayObject.
class ObjectParameter extends ArrayObject {
public function __set($name, $value) {
$this->$name = $value;
}
public function __get($name) {
return $this[$name];
}
}
//creating a new Array object
$objParam = new ObjectParameter;
//adding properties
$objParam->strName = "foo";
//print name
printf($objParam->strName);
//add another property
$objParam->strUser = "bar";
There is a lot you can do with this approach to make it easy for you to create objects even from arrays, hope this helps .
Like the json_decode idea, wrote this:
function a($json) {
return json_decode($json, true); //turn true to false to use objets instead of associative arrays
}
//EXAMPLE
$cat = 'meow';
$array = a('{"value1":"Tester",
"value2":"'.$cat.'",
"value3":{"valueX":"Hi"}}');
print_r($array);

Categories