Result set(Sub Documents) for a mongodb query in php - php

I am trying to get the result set output for a query. I was able to write the query and am getting the required result using var_dump.
$comment = array(
"Name" => array( 'FirstName' => $n1, 'LastName' => $n2 )
);
$cursor= $c_users->find( $comment );
$result = $cursor->getNext();
echo var_dump( $result );
But I am failing when i want to get output for a sub document.
In case of a normal document the below code works:
echo $result['variable'];
But consider a case where there is a document structure given below:
array(
"Name" => array( 'FirstName' => $n1, 'LastName' => $n2 )
);
Could anyone help me with the syntax to output the first name. I was trying with below code
but did not succeed.
echo $result['variable.FirstName']
So the question is how to access embedded document of mongodb using PHP?
Thanks and Regards,
Sai

In order to access embedded document key (property) you need to treat embedded document like an array in PHP dot notation won't work in PHP for MongoDB so you should try:
echo $result['Name']['FirstName'];
Accessing embedded document with dot notation will work in mongoshell not in PHP driver.

Related

YouTube Feed has an object called #attributes how can I access it?

I am trying to get a YouTube RSS feed to work but I am struggling to get one of the attributes I need out of it. I have never seen part of the array starting with an # sign so I think it may be some sort of a special element but I'm not sure. Code below and what I have already tried after.
Feed:
<?php
$xml->entry =
SimpleXMLElement::__set_state(array(
'id' => 'yt:video:DjwM9SHJznM',
'title' => 'JD19AT - Joomla! in der Uni - Community-Arbeit als Lehrveranstaltung',
'link' =>
SimpleXMLElement::__set_state(array(
'#attributes' =>
array (
'rel' => 'alternate',
'href' => 'https://www.youtube.com/watch?v=DjwM9SHJznM',
),
)),
'author' =>
SimpleXMLElement::__set_state(array(
'name' => 'J and Beyond e.V.',
'uri' => 'https://www.youtube.com/channel/UCy6ThiEDnalZOd_pgtpBk1Q',
)),
'published' => '2019-03-30T16:49:53+00:00',
'updated' => '2019-05-09T16:56:18+00:00',
));
?>
Code:
$feed = $youtubeChannelFeed;
$xml = simplexml_load_file($feed);
$html = "";
This works $xml->entry->title;
but this doesn't $xml->entry->link it just says "SimpleXML Object"
As it says object I then tried using both -> arrow and ['attribute'] notation.
I tried escaping the # with a \# but that just caused an error.
How can I traverse the tree and get the value of to #attributes->href ?
The way I always try to remember this is that you can use an arrow or brackets to access data in an array or object.
Array begins with A, but it chooses the one that's does not begin with A. Object is the one left over. That's how I remember it at least.
In this case, although it was calling it a SimpleXMLObject it was actually showing me that it's an array in the print_r. So I had to use brackets to access like so:
$xml->entry->link[0]['href']
I couldn't work out how to access #attributes but I remember now that you don't need to know the name to access it, you can do it using number format too.
If I'm honest I don't really know how I could access the first part with arrows as that appears to be an array too.

PhP returning Json in []

Hey I am trying to pass data back in json format using json_encode.
However it seems to return like this:
[{‘county’:’us’,’sector’:’retail’}]
However the end user has said that they expect the response without the square brackets.
How do I do this?
Thanks.
Depends on how you are generating the value you encode... json_encode has an option JSON_FORCE_OBJECT you could use but from what I can see that's probably not what you want, as it seems to me this would only turn the "square brackets" into a wrapper object. Nevertheless, if you'd like to try:
json_encode($value, JSON_FORCE_OBJECT);
Edit: as others have said, it seems likely json_encode($value[0]) is what you want.
Assuming your array is:
$data = [
'country' => 'us',
'sector' => 'retail',
];
Then just return a json_encoded array like so:
json_encode($data);
// {"country":"us","sector":"retail"}
However, if your array with data is "nested" like so:
$data = [[
'country' => 'us',
'sector' => 'retail',
]];
then return the encoded first element of it:
json_encode($data[0]);
// {"country":"us","sector":"retail"}
My experience of this happening is that you're accidentally storing your data as the first item of an array.
For example you may have done:
$json_store = Array();
$json_store[] = Array('country' => 'us', 'sector' => 'retail');
$json = json_encode($json_store);
A way of testing for this is to see if doing the following removes the brackets:
$json_encode($json_store[0])
If it does, you've a unnecessarily nested array that you should fix. Using the above line probably should be avoided as it's better to fix how the data is stored in the first place.

Deleting a document based off of it's ObjectId [duplicate]

I was successful in deleting documents using other fields but could not delete using "_id" field. The PHP page says that the id should be a string (which it is by default), but what I was trying to do is, giving an id of my own which is an integer, and am doing the following:
This is my document structure:
$document = array (
'_id' => new MongoInt32(1),
'cust_id' => 'abc124'
)
This is how I am trying to delete:
$collection->remove(array('_id' => new MongoId(1)), true);
But this is giving me an error. PHP php manual says:
"To remove a document based on its ID, you need to ensure that you pass the ID as a MongoID object rather than just a string:"
But my id is a int and I cant figure out the process to delete the document referenced by the id.
Your help would be appreciated. Thank You.
You've used a normal integer (MongoInt32) as _id field. And MongoInt32 is not the same as MongoID. They are two different classes. You are suppose to delete it with:
$collection->remove( array( '_id' => new MongoInt32(1) ) );
Additional Information:
MongoId is used as value for an _id field if you don't set a value yourself, such as with:
$collection->insert( array( 'cust_id' => 'abc124' ) );
If you retrieve this document, and var_dump() that you will see:
array(2) {
'_id' =>
class MongoId#6 (1) {
public $$id =>
string(24) "51ee74e944670a09028d4fc9"
}
'cust_id' =>
string(6) "abc124"
}
The note in the docs mean that you can't remove that document now with:
$collection->remove( array( '_id' => '51ee74e944670a09028d4fc9' ) );
But instead you will need to use:
$collection->remove( array( '_id' => new MongoID( '51ee74e944670a09028d4fc9' ) ) );
As last point I'd like to raise that you don't really have to use new MongoInt32(1) in the first place, you can just use:
$document = array (
'_id' => 1,
'cust_id' => 'abc124'
);
You only need MongoInt32/MongoInt64 in case you're on a 32-bit platform (or Windows) and need to deal with large numbers.
This should work:
$collection->deleteOne( array( '_id' => new MongoDB\BSON\ObjectId ($_id )) );
"To remove a document based on its ID, you need to ensure that you pass the ID as a MongoID object rather than just a string:"
Normally what the PHP manual states is true but not for you. You have changed the type of your _id to something other than an ObjectId (aka a MongoId).
With this in mind you need to search by that other object which is a MongoInt32:
$db->collection->remove(array('_id'=>new MongoInt32(1)))

PHP: How do I echo the results of this array?

$header_content = array();
$header_content['pageone'][] = array(
'image' => 'photo-one.png',
'desc' => "One. Some text here.",
);
$header_content['pagetwo'][] = array(
'image' => 'photo-two.png',
'desc' => "Two. Some text here.",
);
I do not want to echo the entire array, just certain parts when called... like $header_content['pageone']['image'], except this doesn't work... How do you go about echoing parts of an array?
I have searched but it's all a little confusing right now for me. Thanks.
Define it like -
$header_content['pagetwo'] = array(
'image' => 'photo-two.png',
'desc' => "Two. Some text here.",
);
The keys are different pageone, pagetwo. No need of that extra index i think. And then access it - echo $header_dontent['pagetwo']['image'];
For printing array values, you can use :
print_r function
Example : print_r($array)
Specific key data can be accessed through : print_r($array[$key])
OR
var_dump function
Example : var_dump($array)
Specific key data can be accessed through : var_dump($array[$key])
use it like $header_content['pageone'][0]['image']
Since
$header_content['pageone'][] = array();
[] appends an element at the end of an array.

PHP dump variable as PHP code

I'm looking for a function to dump a multi-dimension array so that the output is valid php code.
Suppose I have the following array:
$person = array();
$person['first'] = 'Joe';
$person['last'] = 'Smith';
$person['siblings'] = array('Jane' => 'sister', 'Dan' => 'brother', 'Paul' => 'brother');
Now I want to dump the $person variable so the the dump string output, if parsed, will be valid php code that redefines the $person variable.
So doing something like:
dump_as_php($person);
Will output:
$person = array(
'first' => 'Joe',
'last' => 'Smith',
'siblings' => array(
'Jane' => 'sister',
'Dan' => 'brother',
'Paul' => 'brother'
)
);
var_export()
var_export() gets structured
information about the given variable.
It is similar to var_dump() with one
exception: the returned representation
is valid PHP code.
serialize and unserialize
This is useful for storing or passing PHP values around without losing their type and structure. In contrast to var_export this will handle circular references as well in case you want to dump large objects graphs.
The output will not be PHP code though.

Categories