MongoDB use $in 2 times in a single request - php

Is it possible to do two or more $in in one request ?
My code :
find({_id: { $in: [ObjectId("5e96c5b11000ae32d0742d94")] } })
Here I want to do another $in to filter my MongoDB.
(I can show you the structure of my base if anyone want it)
Hopefully it's clear.
Here is the result of a find() (here is only 6 adress I have a lot more but we don't care) :
object(MongoDB\Model\BSONDocument)#5604 (1) { ["storage":"ArrayObject":private]=> array(2) { ["_id"]=> object(MongoDB\BSON\ObjectId)#5630 (1) { ["oid"]=> string(24) "5e96c5b11000ae32d0742d94" } [0]=> string(5104518) "
{"id":"05009","type":"municipality","name":"Aspres-lès-Corps","postcode":["05800"],"citycode":"05009","lon":6.0005,"lat":44.8118,"x":937174.73,"y":6417022.74,"population":107,"city":"Aspres-lès-Corps","context":"05, Hautes-Alpes, Provence-Alpes-Côte d'Azur","importance":0.18009340385621533}
{"id":"05024","type":"municipality","name":"Valdoule","postcode":["05150"],"citycode":"05024","lon":5.5233,"lat":44.4615,"x":900711.69,"y":6376812.41,"population":212,"city":"Valdoule","context":"05, Hautes-Alpes, Provence-Alpes-Côte d'Azur","importance":0.21360128697297767}
{"id":"05031","type":"municipality","name":"Champcella","postcode":["05310"],"citycode":"05031","lon":6.5242,"lat":44.7193,"x":979003.59,"y":6408468.91,"population":185,"city":"Champcella","context":"05, Hautes-Alpes, Provence-Alpes-Côte d'Azur","importance":0.20689148370809196}
{"id":"05032","type":"municipality","name":"Champoléon","postcode":["05260"],"citycode":"05032","lon":6.2619,"lat":44.7429,"x":958141.88,"y":6410195.7,"population":144,"city":"Champoléon","context":"05, Hautes-Alpes, Provence-Alpes-Côte d'Azur","importance":0.19459101490553132}
{"id":"05033","type":"municipality","name":"Chanousse","postcode":["05700"],"citycode":"05033","lon":5.6606,"lat":44.3633,"x":911996.46,"y":6366268.17,"population":40,"city":"Chanousse","context":"05, Hautes-Alpes, Provence-Alpes-Côte d'Azur","importance":0.13312939135127264}
{"id":"05035","type":"municipality","name":"Châteauneuf-d'Oze","postcode":["05400"],"citycode":"05035","lon":5.8979,"lat":44.5038,"x":930323.7,"y":6382530.99,"population":28,"city":"Châteauneuf-d'Oze","context":"05, Hautes-Alpes, Provence-Alpes-Côte d'Azur","importance":0.11676874579085184}
And here is where I am taking the file :
https://adresse.data.gouv.fr/data/ban/adresses/latest/addok/adresses-addok-05.ndjson.gz
I import data via a controller in php :
$connection = new MongoClient();
$db = $connection->france;
$collection = $db->adress05;
$collection->insert($jsonarray);
And I am converting it like this :
$ndjsongz=file_get_contents('https://adresse.data.gouv.fr/data/ban/adresses/latest/addok/adresses-addok-05.ndjson.gz');
$ndjson=gzdecode($ndjsongz);
$bsonarray=explode("}",$ndjson, true);
$json = MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($bsonarray));
$jsonarray = json_decode($json);
Thanks

Here's the syntax for an $and with multiple $in statements
find({
$and: [{
_id: {
$in: [ObjectId('99500b4eb8ee4c8c6f129d86'),...]
}
}, {
_id: {
$in:[ObjectId('b81f234213f87fd0bc1ddd97'),...]
}
}
]})

Related

Format array of objects for possible json output for Postman/GET requests

So I can't seem to figure this out, so I'm reaching out to see if someone might be able to help me.
Please let me know what the best output is so that I could use GET to retrieve clean data for the endpoint that I've created.
I have the following method:
function instagram_posts(): bool|string
{
if (!function_exists('is_plugin_active')) {
include_once(ABSPATH . 'wp-admin/includes/plugin.php');
}
if (!is_plugin_active('fh-instagram/autoload.php')) {
return false;
}
if (empty($items = Instagram::get_items_for_api(50))) {
return false;
}
var_dump($items);
var_dump(json_encode($items));
return json_encode($items);
}
var_dump($items); gives me the following output:
array(50) {
[0]=>
object(Plugin\Instagram\Item)#976 (7) {
["id":"Plugin\Instagram\Item":private]=>
}
[1]=>
object(Plugin\Instagram\Item)#1030 (7) {
["id":"Plugin\Instagram\Item":private]=>
string(17) "17842233125750202"
}
}
When I run var_dump(json_encode($items)); I get the following output:
string(151) "[{},{}]"
How can I convert my array of objects so that it can transform it to json and then use it within Postman? This is what it currently looks like in Postman:
array(50) {
[0]=>
object(Plugin\Instagram\Item)#973 (7) {
["id":"Plugin\Instagram\Item":private]=>
string(17) "17992874035441353"
}
[1]=>
object(Plugin\Instagram\Item)#1027 (7) {
["id":"Plugin\Instagram\Item":private]=>
string(17) "17842233125750202"
}
}
It should be outputted such as:
[
{"id": etc..}
]
All help will be appreciated!
The instagram_posts method is being use below:
add_action('rest_api_init', function () {
register_rest_route( 'instagram', '/posts/', [
'methods' => 'GET',
'callback' => 'instagram_posts',
]);
});
So I can use Postman to access the endpoint: http://headlesscms.com.local/wp-json/instagram/posts
Since the property you want is private, it won't be included in the results of json_encode(). Only public properties will.
You need to create a multidimensional array with the structure you want and encode that.
// This is the new array we will push the sub arrays into
$results = [];
foreach($items as $item) {
$results[] = ['id' => $item->get_id()];
}
return json_encode($results);
This will give you a json structure that looks like:
[
{
"id": 1
},
{
"id": 2
},
...
]
Alternative format
If you only want a list of id's, you might not need to create a multidimensional array, but rather just return a list of ids.
In that case, do this:
$results = [];
foreach ($items as $item) {
$results[] = $item->get_id();
}
return json_encode($results);
That would give you:
[
1,
2,
...
]

Can't access to json position in foreach

I'm trying to get all values of this JSON:
{"_links":[{"self":"http://api.football-data.org/alpha/soccerseasons/394/teams"},{"soccerseason":"http://api.football-data.org/alpha/soccerseasons/394"}],"count":18,"teams":[{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/5"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/5/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/5/players"}},"name":"FC Bayern München","code":"FCB","shortName":"Bayern","squadMarketValue":"551,250,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/commons/c/c5/Logo_FC_Bayern_München.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/7"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/7/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/7/players"}},"name":"Hamburger SV","code":"HSV","shortName":"HSV","squadMarketValue":"71,100,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/commons/6/66/HSV-Logo.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/16"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/16/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/16/players"}},"name":"FC Augsburg","code":"FCA","shortName":"Augsburg","squadMarketValue":"48,550,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/de/b/b5/Logo_FC_Augsburg.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/9"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/9/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/9/players"}},"name":"Hertha BSC","code":"BSC","shortName":"Hertha","squadMarketValue":"63,700,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/de/8/81/Hertha_BSC_Logo_2012.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/3"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/3/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/3/players"}},"name":"Bayer Leverkusen","code":"B04","shortName":"Leverkusen","squadMarketValue":"177,100,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/de/9/95/Bayer_04_Leverkusen_Logo.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/2"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/2/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/2/players"}},"name":"TSG 1899 Hoffenheim","code":"TSG","shortName":"Hopenhoam","squadMarketValue":"118,200,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/de/e/e7/Logo_TSG_Hoffenheim.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/55"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/55/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/55/players"}},"name":"SV Darmstadt 98","code":"DAR","shortName":"Darmstadt","squadMarketValue":"12,450,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/de/8/87/Svdarmstadt98.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/8"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/8/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/8/players"}},"name":"Hannover 96","code":"H96","shortName":"Hannover","squadMarketValue":"74,500,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/de/c/cd/Hannover_96_Logo.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/15"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/15/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/15/players"}},"name":"1. FSV Mainz 05","code":"M05","shortName":"Mainz","squadMarketValue":"75,200,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/de/0/0b/FSV_Mainz_05_Logo.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/31"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/31/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/31/players"}},"name":"FC Ingolstadt 04","code":"FCI","shortName":"Ingolstadt","squadMarketValue":"18,600,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/de/5/55/FC-Ingolstadt_logo.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/12"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/12/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/12/players"}},"name":"Werder Bremen","code":"SVW","shortName":"Bremen","squadMarketValue":"52,600,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/commons/b/be/SV-Werder-Bremen-Logo.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/6"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/6/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/6/players"}},"name":"FC Schalke 04","code":"S04","shortName":"Schalke","squadMarketValue":"208,850,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/de/6/6d/FC_Schalke_04_Logo.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/4"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/4/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/4/players"}},"name":"Borussia Dortmund","code":"BVB","shortName":"Dortmund","squadMarketValue":"317,800,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/commons/6/67/Borussia_Dortmund_logo.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/18"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/18/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/18/players"}},"name":"Bor. Mönchengladbach","code":"BMG","shortName":"M'gladbach","squadMarketValue":"130,450,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/de/c/cc/Borussia_Moenchengladbach_Logo.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/11"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/11/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/11/players"}},"name":"VfL Wolfsburg","code":"WOB","shortName":"Wolfsburg","squadMarketValue":"206,350,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/de/b/bc/VfL_Wolfsburg_Logo_weiß.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/19"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/19/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/19/players"}},"name":"Eintracht Frankfurt","code":"SGE","shortName":"Eintr. Frankfurt","squadMarketValue":"69,050,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/commons/0/04/Eintracht_Frankfurt_Logo.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/10"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/10/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/10/players"}},"name":"VfB Stuttgart","code":"VFB","shortName":"Stuttgart","squadMarketValue":"89,050,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/commons/a/ab/VfB_Stuttgart_Logo.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/1"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/1/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/1/players"}},"name":"1. FC Köln","code":"EFFZEH","shortName":"Köln","squadMarketValue":"42,150,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/de/1/16/1._FC_Köln.svg"}]}
I've created this decoder
$decoded = json_decode($response,true);
so I perform a foreach to iterate through the object:
foreach($decoded['teams'] as $team => $value)
{
var_dump($decoded['_links']['self']['href');
}
but this code return a NULL object. I want get this content:
{"_links":[{"self":"http://api.football-data.org/alpha/soccerseasons/394/teams"},
json structure:
{
"_links": {
"self": { "href": "http://api.football-data.org/alpha/teams/19" },
"fixtures": { "href": "http://api.football-data.org/alpha/teams/19/fixtures" },
"players": { "href": "http://api.football-data.org/alpha/teams/19/players" }
},
"name": "Eintracht Frankfurt",
"code": "SGE",
"shortName": "Eintr. Frankfurt",
"squadMarketValue": "75.475.000 ?",
"crestUrl": "http://upload.wikimedia.org/wikipedia/commons/0/04/Eintracht_Frankfurt_Logo.svg"
}
What I doing wrong?
From your comment, we can see
array(3) {
["_links"]=> array(2) {
[0]=> array(1) {
["self"]=> string(58) "api.football-data.org/alpha/soccerseasons/394/teams"; }
[1]=> array(1) {
["soccerseason"]=> string(52) "api.football-...";}
}
So, to get your "self" value, you must access $decoded["_links"][0]["self"]
You are using $decoded var in place of $value. It should be like this:
foreach($decoded['teams'] as $team => $value)
{
var_dump($value['_links']['self']['href']);
}
Update
To get self link of json you don't need to iterate over teams. You should iterate over _links like that:
foreach($decoded['_links'] as $link)
{
var_dump(reset($link));
}
To get only first link (only if document structure will never change) you need only one line:
var_dump($decoded['_links'][0]['self']);

mongodb php get array value

I am trying to get ONE value from a sub document of a stored doc.
a sample document looks like this and I'm trying to get the value "doc2":
{
"_id" : ObjectId("52060cae8b080ed4170063d3"),
"form_id" : "5204c6dca0875b6a1545f436",
"update" : false,
"values" : [{
"5204c71a8b080e6c190000bb" : "doc2"
}, {
"5204c7638b080e6c19006b06" : "that one too"
}, {
"form_id" : "5204c6dca0875b6a1545f436"
}, {
"btn_submit" : "Save"
}]
}
so far my code looks like this:
try {
$connection = new Mongo();
$database = $connection->selectDB('forms');
$collection = $database->selectCollection('instance');
} catch(MongoConnectionException $e) {
die("Failed to connect to database ".$e->getMessage());
}
$value = $collection->findOne(array('_id' =>new MongoId($instid)),array('values.'.$fid));
$instid is passed in and is form_id in the document. And $fid is passed in and is the key in the values array in the document
and I'm getting this:
{ ["_id"]=> object(MongoId)#15 (1)
{ ["$id"]=> "52060cae8b080ed4170063d3" }
["values"]=>
{ [0]=> { ["5204c71a8b080e6c190000bb"]=> "doc2" }
[1]=> array(0) { }
[2]=> array(0) { }
[3]=> array(0) { }
} }
Thanks in advance for any assistance.
You are getting data in form of multidimensional Array, So you should use
print_r($value['values']['0']);
This will return
Array ( [5204c71a8b080e6c190000bb] => doc2 )
And if you only want to echo out doc2 then you can use foreach statement
foreach($value['values']['0'] as $x)
{
echo $x;
}

Convert multidimensional objects to array [duplicate]

This question already has answers here:
Convert a PHP object to an associative array
(33 answers)
Closed 6 months ago.
I'm using amazon product advertising api. Values are returned as a multidimensional objects.
It looks like this:
object(AmazonProduct_Result)#222 (5) {
["_code":protected]=>
int(200)
["_data":protected]=>
string(16538)
array(2) {
["IsValid"]=>
string(4) "True"
["Items"]=>
array(1) {
[0]=>
object(AmazonProduct_Item)#19 (1) {
["_values":protected]=>
array(11) {
["ASIN"]=>
string(10) "B005HNF01O"
["ParentASIN"]=>
string(10) "B008RKEIZ8"
["DetailPageURL"]=>
string(120) "http://www.amazon.com/Case-Logic-TBC-302-FFP-Compact/dp/B005HNF01O?SubscriptionId=AKIAJNFRQCIJLTY6LDTA&tag=*********-20"
["ItemLinks"]=>
array(7) {
[0]=>
object(AmazonProduct_ItemLink)#18 (1) {
["_values":protected]=>
array(2) {
["Description"]=>
string(17) "Technical Details"
["URL"]=>
string(217) "http://www.amazon.com/Case-Logic-TBC-302-FFP-Compact/dp/tech-data/B005HNF01O%3FSubscriptionId%3DAKIAJNFRQCIJLTY6LDTA%26tag%*******-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB005HNF01O"
}
}
[1]=>
object(AmazonProduct_ItemLink)#17 (1) {
["_values":protected]=>
array(2) {
I mean it also has array inside objects. I would like to convert all of them into a multidimensional array.
I know this is old but you could try the following piece of code:
$array = json_decode(json_encode($object), true);
where $object is the response of the API.
You can use recursive function like below:
function object_to_array($obj, &$arr)
{
if (!is_object($obj) && !is_array($obj))
{
$arr = $obj;
return $arr;
}
foreach ($obj as $key => $value)
{
if (!empty($value))
{
$arr[$key] = array();
objToArray($value, $arr[$key]);
}
else {$arr[$key] = $value;}
}
return $arr;
}
function convertObjectToArray($data) {
if (is_object($data)) {
$data = get_object_vars($data);
}
if (is_array($data)) {
return array_map(__FUNCTION__, $data);
}
return $data;
}
Credit to Kevin Op den Kamp.
I wrote a function that does the job, and also converts all json strings to arrays too. This works pretty fine for me.
function is_json($string) {
// php 5.3 or newer needed;
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
function objectToArray($objectOrArray) {
// if is_json -> decode :
if (is_string($objectOrArray) && is_json($objectOrArray)) $objectOrArray = json_decode($objectOrArray);
// if object -> convert to array :
if (is_object($objectOrArray)) $objectOrArray = (array) $objectOrArray;
// if not array -> just return it (probably string or number) :
if (!is_array($objectOrArray)) return $objectOrArray;
// if empty array -> return [] :
if (count($objectOrArray) == 0) return [];
// repeat tasks for each item :
$output = [];
foreach ($objectOrArray as $key => $o_a) {
$output[$key] = objectToArray($o_a);
}
return $output;
}
This is an old question, but I recently ran into this and came up with my own solution.
array_walk_recursive($array, function(&$item){
if(is_object($item)) $item = (array)$item;
});
Now if $array is an object itself you can just cast it to an array before putting it in array_walk_recursive:
$array = (array)$object;
array_walk_recursive($array, function(&$item){
if(is_object($item)) $item = (array)$item;
});
And the mini-example:
array_walk_recursive($array,function(&$item){if(is_object($item))$item=(array)$item;});
In my case I had an array of stdClass objects from a 3rd party source that had a field/property whose value I needed to use as a reference to find its containing stdClass so I could access other data in that element. Basically comparing nested keys in 2 data sets.
I have to do this many times, so I didn't want to foreach over it for each item I need to find. The solution to that issue is usually array_column, but that doesn't work on objects. So I did the above first.
Just in case you came here as I did and didn't find the right answer for your situation, this modified version of one of the previous answers is what ended up working for me:
protected function objToArray($obj)
{
// Not an object or array
if (!is_object($obj) && !is_array($obj)) {
return $obj;
}
// Parse array
foreach ($obj as $key => $value) {
$arr[$key] = $this->objToArray($value);
}
// Return parsed array
return $arr;
}
The original value is a JSON string. The method call looks like this:
$array = $this->objToArray(json_decode($json, true));

Using json_encode on objects in PHP (regardless of scope)

I'm trying to output lists of objects as json and would like to know if there's a way to make objects usable to json_encode? The code I've got looks something like
$related = $user->getRelatedUsers();
echo json_encode($related);
Right now, I'm just iterating through the array of users and individually exporting them into arrays for json_encode to turn into usable json for me. I've already tried making the objects iterable, but json_encode just seems to skip them anyway.
edit: here's the var_dump();
php > var_dump($a);
object(RedBean_OODBBean)#14 (2) {
["properties":"RedBean_OODBBean":private]=>
array(11) {
["id"]=>
string(5) "17972"
["pk_UniversalID"]=>
string(5) "18830"
["UniversalIdentity"]=>
string(1) "1"
["UniversalUserName"]=>
string(9) "showforce"
["UniversalPassword"]=>
string(32) ""
["UniversalDomain"]=>
string(1) "0"
["UniversalCrunchBase"]=>
string(1) "0"
["isApproved"]=>
string(1) "0"
["accountHash"]=>
string(32) ""
["CurrentEvent"]=>
string(4) "1204"
["userType"]=>
string(7) "company"
}
["__info":"RedBean_OODBBean":private]=>
array(4) {
["type"]=>
string(4) "user"
["sys"]=>
array(1) {
["idfield"]=>
string(2) "id"
}
["tainted"]=>
bool(false)
["model"]=>
object(Model_User)#16 (1) {
["bean":protected]=>
*RECURSION*
}
}
}
and here's what json_encode gives me:
php > echo json_encode($a);
{}
I ended up with just this:
function json_encode_objs($item){
if(!is_array($item) && !is_object($item)){
return json_encode($item);
}else{
$pieces = array();
foreach($item as $k=>$v){
$pieces[] = "\"$k\":".json_encode_objs($v);
}
return '{'.implode(',',$pieces).'}';
}
}
It takes arrays full of those objects or just single instances and turns them into json - I use it instead of json_encode. I'm sure there are places I could make it better, but I was hoping that json_encode would be able to detect when to iterate through an object based on its exposed interfaces.
All the properties of your object are private. aka... not available outside their class's scope.
Solution for PHP >= 5.4
Use the new JsonSerializable Interface to provide your own json representation to be used by json_encode
class Thing implements JsonSerializable {
...
public function jsonSerialize() {
return [
'something' => $this->something,
'protected_something' => $this->get_protected_something(),
'private_something' => $this->get_private_something()
];
}
...
}
Solution for PHP < 5.4
If you do want to serialize your private and protected object properties, you have to implement a JSON encoding function inside your Class that utilizes json_encode() on a data structure you create for this purpose.
class Thing {
...
public function to_json() {
return json_encode(array(
'something' => $this->something,
'protected_something' => $this->get_protected_something(),
'private_something' => $this->get_private_something()
));
}
...
}
A more detailed writeup
In PHP >= 5.4.0 there is a new interface for serializing objects to JSON : JsonSerializable
Just implement the interface in your object and define a JsonSerializable method which will be called when you use json_encode.
So the solution for PHP >= 5.4.0 should look something like this:
class JsonObject implements JsonSerializable
{
// properties
// function called when encoded with json_encode
public function jsonSerialize()
{
return get_object_vars($this);
}
}
In RedBeanPHP 2.0 there is a mass-export function which turns an entire collection of beans into arrays. This works with the JSON encoder..
json_encode( R::exportAll( $beans ) );
Following code worked for me:
public function jsonSerialize()
{
return get_object_vars($this);
}
I didn't see this mentioned yet, but beans have a built-in method called getProperties().
So, to use it:
// What bean do we want to get?
$type = 'book';
$id = 13;
// Load the bean
$post = R::load($type,$id);
// Get the properties
$props = $post->getProperties();
// Print the JSON-encoded value
print json_encode($props);
This outputs:
{
"id": "13",
"title": "Oliver Twist",
"author": "Charles Dickens"
}
Now take it a step further. If we have an array of beans...
// An array of beans (just an example)
$series = array($post,$post,$post);
...then we could do the following:
Loop through the array with a foreach loop.
Replace each element (a bean) with an array of the bean's properties.
So this...
foreach ($series as &$val) {
$val = $val->getProperties();
}
print json_encode($series);
...outputs this:
[
{
"id": "13",
"title": "Oliver Twist",
"author": "Charles Dickens"
},
{
"id": "13",
"title": "Oliver Twist",
"author": "Charles Dickens"
},
{
"id": "13",
"title": "Oliver Twist",
"author": "Charles Dickens"
}
]
Hope this helps!
I usually include a small function in my objects which allows me to dump to array or json or xml. Something like:
public function exportObj($method = 'a')
{
if($method == 'j')
{
return json_encode(get_object_vars($this));
}
else
{
return get_object_vars($this);
}
}
either way, get_object_vars() is probably useful to you.
$products=R::findAll('products');
$string = rtrim(implode(',', $products), ',');
echo $string;
Here is my way:
function xml2array($xml_data)
{
$xml_to_array = [];
if(isset($xml_data))
{
if(is_iterable($xml_data))
{
foreach($xml_data as $key => $value)
{
if(is_object($value))
{
if(empty((array)$value))
{
$value = (string)$value;
}
else
{
$value = (array)$value;
}
$value = xml2array($value);
}
$xml_to_array[$key] = $value;
}
}
else
{
$xml_to_array = $xml_data;
}
}
return $xml_to_array;
}
for an array of objects, I used something like this, while following the custom method for php < 5.4:
$jsArray=array();
//transaction is an array of the class transaction
//which implements the method to_json
foreach($transactions as $tran)
{
$jsArray[]=$tran->to_json();
}
echo json_encode($jsArray);

Categories