How to insert array values(php) in MongoDB? - php

My contents of MongoDB(when i used find()) is like this:
{
"_id": ObjectId("50072b17b4a6de3b11000001"),
"addresses": [
{
"_id": ObjectId("50072b17b4a6de3b11000004"),
"address1": "770 27th Ave",
"address2": null,
"city": "San Mateo",
"country": "United States",
"country_code": "US",
"name": "home",
"primary": true,
"state": "California",
"zip": "94403"
}
],
"biography": null,
"category_ids": [],
"department": null,
"emails": [
{
"_id": ObjectId("50072b17b4a6de3b11000003"),
"_type": "Email",
"name": "work",
"email": "alan#altimetergroup.com"
}
]
}
What I need to do is I need to update this MongoDB with additional datas's. For that I need to get the values in php as an array and insert that array in to this collection. How to get the values for these specified fields as an array in php and how to insert those in php??

$array = $this->collection->findOne(array('_id' => MONGO_ID));
//Update things
$this->collection->update(array('_id' => $array['_id']), $array);
MONGO_ID in my example should represent the '_id' MongoDB automatically assigns. Make sure it is sent as an Object, and not as a string.

If you want to add another entry, you add an entry like so:
$this->collection->insert($array_of_data, array('safe' => true));

For insert:
$id = new MongoId();
$test->insert(array('t' => 'test', 'email' => array('_id' => $id, 'email' => 'ccc#ccc.com')));
And the result:
{ "_id" : ObjectId("5088cba86527044a31000001"), "t" : "test", "email" : { "_id" : ObjectId("5088cba86527044a31000000"), "email" : "ccc#ccc.com" } }
It works :)

Related

How to access a json child in php respect validation?

I'm trying to validate the following json file but I can't find the way to access the "Address" child, how should I do it? Everything goes fine until it tries to access the "address" field.
Json:
{
"first_name": "Test",
"last_name": "Test",
"email": "test#gmail.com",
"mobile_phone": 123456789,
"address": {
"country": "Test",
"postal_code": "Test",
"city": "Test",
"street": "Test",
"number": "Test",
"floor": "Test",
"door": "Test"
},
"password": "Test",
"birth_date": "2005-12-30"
}
Code:
$data = $this->validator->validate($request, [
"first_name" => v::stringVal()->notEmpty(),
"last_name" => v::stringVal()->notEmpty(),
"email" => v::notEmpty()->email(),
"mobile_phone" => v::intVal()->notEmpty(),
"address" =>[
"country" => v::stringVal()->notEmpty(),
"postal_code" => v::stringVal()->notEmpty(),
"city" => v::stringVal()->notEmpty(),
"street" => v::stringVal()->notEmpty(),
"number" => v::stringVal()->notEmpty(),
"floor" => v::stringVal()->notEmpty(),
"door" => v::stringVal()->notEmpty(),
],
"password" => v::base64()->notEmpty(),
"birth_date" => v::date()->notEmpty()
]);
Looks like you are using Respect\Validation\Validator. We can make use of chained validation and the Key function to validate sub-arrays as shown in the docs.
$data = [
'parentKey' => [
'field1' => 'value1',
'field2' => 'value2'
'field3' => true,
]
];
Using the next combination of rules, we can validate child keys.
v::key(
'parentKey',
v::key('field1', v::stringType())
->key('field2', v::stringType())
->key('field3', v::boolType())
)
->assert($data); // You can also use check() or validate()
Applied to your data, the validation could look like this:
use Respect\Validation\Validator as v;
$json = json_decode('{
"first_name": "Test",
"last_name": "Test",
"email": "test#gmail.com",
"mobile_phone": 123456789,
"address": {
"country": "Test",
"postal_code": "Test",
"city": "Test",
"street": "Test",
"number": "Test",
"floor": "Test",
"door": "Test"
},
"password": "Test",
"birth_date": "2005-12-30"
}', true);
v::create()
->key('first_name', v::stringType()->length(1, 32))
->key('last_name', v::stringVal()->notEmpty())
//->..
->key('address',
v::key('country', v::stringType()->length(1, 32))
->key('postal_code', v::stringType()->length(1, 32))
->key('city', v::stringType()->length(1, 32))
//->..
)
->key('password', v::stringVal()->notEmpty())
->key('birth_date', v::stringVal()->notEmpty())
->assert($json); // You can also use check() or validate()
That is the way to access the child of the json:
$this->validator->validate($request, [
"first_name" => v::stringVal()->notEmpty(),
"last_name" => v::stringVal()->notEmpty(),
"email" => v::notEmpty()->email(),
"mobile_phone" => v::intVal()->notEmpty(),
"address" => v::notEmpty()
->key("country", v::stringVal()->notEmpty())->key("postal_code", v::stringVal())->key("city", v::stringVal()->notEmpty())->key("street", v::stringVal()->notEmpty())->key("number", v::stringVal())->key("floor", v::stringVal())->key("door", v::stringVal()),
"password" => v::base64()->notEmpty(),
"birth_date" => v::date('d/m/Y')->notEmpty()
]);

PHP. change value in Array of Arrays not working

very weird issue: I try to change a json string using json_encode and json_decode. I converted the json string to an array(actually it's array of arrays) and try to change some data in it. but I couldn't get the data changed in inner array somehow.
$jsondata = ' {
"Id": "0400006",
"LastName": "Lincoln",
"FirstName": "Abraham",
"PreferredName": "Mr. Abraham Lincoln",
"BirthDate": "1992-06-20T00:00:00",
"PreferredEmailAddress": null,
"Addresses": [
{
"AddressId": "297143",
"Type": "Home",
"AddressLines": [
"201 S Grant Ave"
],
"AddressModifier": "",
"City": "Columbus",
"State": "OH",
"PostalCode": "43215",
"County": "049",
"Country": "",
"RouteCode": "",
"PhoneNumbers": [
{
"Number": "614-555-6666",
"Extension": "",
"TypeCode": "HOME"
}
],
"AddressLabel": [
"201 S Grant Ave",
"Columbus, OH 43215"
],
"PersonId": "0400006",
"EffectiveStartDate": "2008-06-13T00:00:00",
"EffectiveEndDate": null,
"IsPreferredAddress": true,
"IsPreferredResidence": true,
"TypeCode": "H",
"CountryCode": ""
},
{
"AddressId": "727032",
"Type": "Web Address",
"AddressLines": [
"285 E. Main Ave",
"Apt B"
],
"AddressModifier": "",
"City": "Columbus",
"State": "OH",
"PostalCode": "43215",
"County": "049",
"Country": "",
"RouteCode": "",
"PhoneNumbers": [
{
"Number": "614-555-6666",
"Extension": "",
"TypeCode": "HOME"
}
],
"AddressLabel": [
"285 E. Main Ave",
"Apt B",
"Columbus, OH 43215"
],
"PersonId": "0400006",
"EffectiveStartDate": "2018-06-25T00:00:00",
"EffectiveEndDate": null,
"IsPreferredAddress": false,
"IsPreferredResidence": false,
"TypeCode": "WEB",
"CountryCode": ""
}
],
"EmailAddresses": [],
"Phones": [
{
"Number": "614-555-6666",
"Extension": "",
"TypeCode": "HOME"
}
],
"AddressConfirmationDateTime": null,
"EmailAddressConfirmationDateTime": null,
"PhoneConfirmationDateTime": null,
"LastChangedDateTime": "2018-06-27T20:42:22Z",
"ChosenFirstName": "",
"ChosenMiddleName": "",
"ChosenLastName": "",
"PersonalPronounCode": "",
"IsDeceased": false
}
';
$newAddressData = [
"address1" => "5857 Newbridge Dr.",
"address2" => "Apt D",
"city" => "Chicago",
"state" => "Illions",
"postalcode" => "23456"
];
public function modifyData($jsonStr, $newAddressData){
$personInfoData = json_decode($jsonStr, true);
$addressArray = $personInfoData['Addresses'];
$webAddressObj = null;
foreach($addressArray as $address){
if($address['Type'] == 'Web Address' ){
$webAddressObj = &$address;
break;
}
}
if($webAddressObj != null){
echo("update it!");
$webAddressObj['AddressId'] ='';
$webAddressObj['PhoneNumbers']=[];
$webAddressObj['AddressLabel'] =[];
$webAddressObj['AddressLines'] =[$newAddressData['address1'], $newAddressData['address2']];
$webAddressObj['EffectiveStartDate']='';//2018-06-25T00:00:00
$webAddressObj['City']=$newAddressData['city'];
$webAddressObj['State']=$newAddressData['state'];
$webAddressObj['PostalCode']=$newAddressData['postalcode'];
}else{
echo("new address");
$newAddress = new AddressInfo();
$newAddress->Type = "Web Address";
$newAddress->TypeCode = "WEB";
$newAddress->AddressLines =[$newAddressData['address1'], $newAddressData['address2']];
$newAddress->EffectiveStartDate ='';
$newAddress->City = $newAddressData['city'];
$newAddress->State=$newAddressData['state'];
$newAddress->PostalCode=$newAddressData['postalcode'];
$newAddressJson = json_encode($newAddress);
$addressArray[] = $newAddressJson;
}
print_r($webAddressObj);
echo "<p>";
print_r($addressArray);
echo "<p>";
return $personInfoData;
}
$personalInfoData = modifyData($jsondata, $newAddressData);
echo json_encode($personalInfoData);
========================================
You'll find out the $personalInfoData didn't get changed.
This: $webAddressObj = &$address; does not create a reference to that element of the original array. It creates a reference to the temporary copy of the element created by foreach. The reference to that copy does stay set after you've broken out of the loop, but making changes to it will not affect the original array.
If you want a reference to the original element, You'll also need to assign $addressArray by reference to begin with.
$addressArray = &$personInfoData['Addresses'];
you'll need to maintain the reference in the foreach loop, like
foreach($addressArray as &$address){
And you'll still need to assign by reference inside the loop as you're currently doing.
$webAddressObj = &$address;
Rather than keeping track of all the references, it may be easier to follow if you refer directly to the original array by key instead.
$webAddressKey = null;
foreach($addressArray as $key => $address){
if($address['Type'] == 'Web Address' ){
$webAddressKey = $key;
break;
}
}
if($webAddressKey != null){
echo("update it!");
$personInfoData['Addresses'][$webAddressKey]['AddressId'] ='';
...
}

Getting information from nested arrays php

I am making calls to an API
I have the response as an associative array so that I can use:
$field = $response['nameOfKey'];
However, some of the values for keys are themselves arrays like the following:
{
"Title": "Mr",
"Forenames": "Steve",
"Surname": "Williams",
"CountryOfBirth": 1,
"EmailAddress": "john.doe#email.com",
"EmailType": "Personal",
"BirthDate": "\/Date(632880000000)\/",
"Suffix": null,
"NationalInsuranceNumber": null,
"PrimaryAddress": {
"Address1": "Flat 1",
"Address2": "Oxford Street",
"City": "London",
"County": "London",
"Postcode": "L12456",
"Country": 1
},
"AdditionalAddresses": [
{
"Address1": null,
"Address2": null,
"City": null,
"County": null,
"Postcode": null,
"Country": 0,
"AddressType": 0
}
],
"PrimaryTelephone": {
"Number": "123456789",
"DialingCode": 1,
"TelephoneType": 1
},
"AdditionalTelephone": [
{
"Number": "223456789",
"DialingCode": 2,
"TelephoneType": 2
}
],
"BankAccount": {
"AccountName": "John Doe Account",
"AccountNumber": "123456789",
"SortCode": "123456"
},
"PrimaryCitizenship": {
"CountryOfResidency": 1,
"TaxIdentificationNumber": "AB12CD34EF56"
},
"AdditionalCitizenship": [
{
"CountryOfResidency": 0,
"TaxIdentificationNumber": null
}
],
"ExternalCustomerId": "91",
"ExternalPlanId": "91",
"PlanType": 10
}
So at the moment to get Forename I can just do $forename = $decodedResponse["Forenames"]; but I'm quite baffled at trying to get values from the inner arrays.
I thought I could do something like this:
foreach($decodedResponse as $data)
{
foreach($data['TelephoneNumbers'] as $tel)
{
echo $tel['Number']; die();
}
}
Essentially loop through the original Associative array and then loop through a specific key to get its values.
Your should use foreach for following array items: AdditionalAddresses, AdditionalTelephone and AdditionalCitizenship. Otherwise just chain array keys. See examples:
$forename = $decodedResponse['Forenames'];
$address2 = $decodedResponse['PrimaryAddress']['Address2'];
foreach ($decodedResponse['AdditionalTelephone'] as $tel) {
echo $tel['Number'];
}

Nested JSON Object with array in PHP

I want JSON object as follows in that personal, address and itm have sequence of json object.
{
"id": "1",
"state": "12",
"personal": [
{
"name": "abc",
"contact":"1111111"
"address": [
{
"line1": "abc",
"city": "abc",
"itm": [
{
"num": 1,
"itm_detatils": {
"itemname": "bag",
"rate": 1000,
"discount": 0,
}
}
],
"status": "Y"
}
]
}
]
}
But I am getting result as follows in that I want json array at address and itm_details.
{
"id": "1",
"state": "12",
"personal": [
{
"name": "abc",
"contact": "1111111",
"address": {
"line1": "abc",
"city": "abc",
"itm": {
"inum": "1",
"itm_detatils": {
"itemname": "bag",
"rate": 1000,
"discount": 0
}
},
"status": "Y"
}
}
]
}
My PHP Code is as follow:
In that I am creating simple array and after that array inside array but during encoding to json it's not showing sequence of json object.
$a=array();
$a["id"]="1";
$a["state"]="12";
$a["personal"]=array();
$a["personal"][]=array(
"name"=>"abc",
"contact"=>"1111111",
"address"=>array(
"line1"=>"abc",
"city"=>"abc",
"itm"=>array(
"inum"=>"1",
"itm_detatils"=>array(
"itemname"=>"bag",
"rate"=>1000,
"discount"=>0,
),
),
"status"=>"Y",
),
);
echo json_encode($a);
Thanks in advance.
Add one more array
//...
"address" => array(
array(
"line1"=>"abc",
"city"=>"abc",
// ...
),
)

Null values added to JSON file

I'm just starting out in Angular and I'm trying to update my JSON file with a PHP script. The script updates it with the right keys but null values. I'd really appreciate some help.
Here's my code:
<?php
$object_data = array(
'capital' => $_POST['in1'],
'country' => $_POST['in2'],
'continent' => $_POST['in3'],
'image' => $_POST['in4']
);
$capitals = file_get_contents('capitals.json');
$capital_data = json_decode($capitals);
array_push($capital_data,$object_data);
$jsondata = json_encode($capital_data,JSON_PRETTY_PRINT);
file_put_contents('capitals.json',$jsondata);
?>
And here's my JSON file:
[
{
"capital": "Ottawa",
"country": "Canada",
"continent": "North America",
"image": "https:\/\/upload.wikimedia.org\/wikipedia\/commons\/2\/22\/Parliament-Ottawa.jpg"
},
{
"capital": "Oslo",
"country": "Norway",
"continent": "Europe",
"image": "https:\/\/upload.wikimedia.org\/wikipedia\/commons\/thumb\/b\/bd\/Downtown_Oslo_Norway_skyline.png\/800px-Downtown_Oslo_Norway_skyline.png"
},
{
"capital": "Auckland",
"country": "New Zealand",
"continent": "Oceania",
"image": "https:\/\/upload.wikimedia.org\/wikipedia\/commons\/6\/6e\/Auckland_City_from_Mt_Victoria%2C_Devonport_-_Flickr_-_111_Emergency_%281%29.jpg"
}
]
Lastly, here's my post request in Angular:
$http.post('capitalData.php',
{"capital":input1.val(),"country":input2.val(),
"continent":input3.val(),"image":input4.val()}).success(function(){
alert("Added!");
});
Edit: Updated the post request to specify which data I'm sending but it still returns nulls.

Categories