mongodb php get array value - php

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;
}

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,
...
]

MongoDB use $in 2 times in a single request

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'),...]
}
}
]})

Add array in array of arrays

I have a $_SESSION index called "items".
Just like this:
$_SESSION['items'];
When user click to add item I check if $_SESSION['items'] exists. If exists, then insert the item, if not, create and insert. Ok.
So I coded this solution:
$newItem = array(
'id'=>$this->getId(),
'red'=>$this->getRef()
);
if(isset($_SESSION['items'])) {
array_push($_SESSION['items'],$newItem);
} else {
$_SESSION['items'] = $newItem;
}
Ok.
The problem is:
If the "else" occurs, the $newItem array is pushed into $_SESSION['items'] with this structure:
{
0: {
id: "1",
ref: "0001",
}
}
Exactly as I was expecting.
But if the "if" statement occurs, my $_SESSION['item'] looses the new indexes and I get a structure like this:
{
0: {
id: "1",
ref: "0001",
},
id: "2",
ref: "0001",
}
As you can see, the new item is not set as array...
If I add more itens, the issue affects only the last item added...
What I am doing wrong?
Change your code to the following:
if (isset($_SESSION['items'])) {
array_push($_SESSION['items'],$newItem);
} else {
$_SESSION['items'] = [];
array_push($_SESSION['items'], $newItem);
}
Now, all the $newItems will be pushed in to an actual array.
Output
array(1) {
["items"]=>
array(2) {
[0]=>
array(2) {
["id"]=>
string(2) "id"
["ref"]=>
string(3) "ref"
}
[1]=>
array(2) {
["id"]=>
string(4) "id-2"
["ref"]=>
string(5) "ref-2"
}
}
}
Live Example
Repl - Dummy data used
Your array_push here seems to be problem, because when you are pushing the array in $_SESSION[‘items’] it takes $newItem array elements and pushes them in the $_SESSION[‘items’]
If you can do as below then it should work
$newItem = array(
'id'=>$this->getId(),
'red'=>$this->getRef()
);
$_SESSION['items'][]= $newItem;

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']);

Can't retrieve associative array index in php

I have an array that looks like the following:
array(3) { [0]=> array(1)
{
["habitacionales"]=> array(1)
{ ["Azcapotzalco"]=> string(1) "3" } }
[1]=> array(1) { ["comerciales"]=> array(0) { } }
[2]=> array(1) { ["industriales"]=> array(0) { } }
}
And I need to check if the array belongs to the type "habitacionales", or "comerciales", etc. But no matter what I do, I keep getting the notice "Undefined index: habitacionales". Could someone point out how to access that index?
I am using cakephp, and I am setting the variables in the controller like this:
$zonasHab = $this->PropiedadesHabitacionale->BasicosPropiedadesHabitacionale->find('list', array('fields'=>array('Zona', 'propiedad_habitacional_id')));
then I do:
$this->set('Zonas', array_unique($linksZonas, SORT_REGULAR));
And finally in the view I do:
foreach ($Zonas as $zona) {
foreach($zona as $zone) {
foreach(array_flip($zone) as $link) {
echo '<li class="dropdownheader">'.$link;
}
var_dump($zone['habitacionales']);
}/*
if($zona['habitacionales']!=null)
foreach(array_flip($zone) as $vinculo) {
echo '<li>'.$this->Html- >link($vinculo, array('controller'=>'propiedadeshabitacionales', 'action'=>'ver', $vinculo)).'</li>';
}
*/
echo '</li>';
}
Just to point out, the wierd thing is that if I do var_dump($zona['habitacionales']); inside the outer foreach, I get the correct value: array(1) { ["Azcapotzalco"]=> string(1) "3" } but I still get the notice appearing telling me it's an undefined index, and I can't use that same syntax ($zona['habitacionales'] for a condition or anything else.
Assuming $Zonas is that array above, try:
foreach($zona as $zone) {
foreach(array_flip($zone) as $link) {
echo '<li class="dropdownheader">'.$link;
}
var_dump($zone);
habitacionales is the key, if you want to access that then use:
foreach($zona as $key => $zone) {
And $key should be set to habitacionales.

Categories