How to parse multi associative arrays to echo out by key values - php

Hey guys Im a student and my question might seem simple but i can't find the right answer anywhere. Please take a look. as you can see $parsed_json works fine with this code $parsed_json = $parsed_json['photos']; how do i add another key of the array there? i tried $parsed_json = $parsed_json[(['photos']['contactInfo'])]; but did now work. Any help will much appreciated. Thank you.
<?php
$json_string = file_get_contents("api/goes/here")
$parsed_json = json_decode($json_string, true);
print_r($parsed_json);
$parsed_json = $parsed_json[(['photos']['contactInfo'])];
foreach($parsed_json as $key => $value)
{
echo $value['typeName'] . '<br>';
echo $value['typeId'] . '<br>';
echo $value['familyName'] . '<br>';
// etc
?>
-------------JSON CONTENT------------------------------
{
"status" : 200,
"requestId" : "0ef05ee4-6bab-4488-a80c-04ce050ca074",
"likelihood" : 0.95,
"photos" : [ {
"type" : "linkedin",
"typeId" : "linkedin",
"typeName" : "LinkedIn",
"url" : "https://d2ojpxxtu63wzl.cloudfront.net/static/651f183b3a1bd463ef5298a2877f2c4f_0c027087db5cd03d244a7dd42e42fc969fa8d636bffd7635b46172c8a597aa73",
"isPrimary" : true
}, {
"type" : "twitter",
"typeId" : "twitter",
"typeName" : "Twitter",
"url" : "https://d2ojpxxtu63wzl.cloudfront.net/static/d0080f4ccd9ea21340b0fd994f82c0e0_2acdc7de41111f7d58e7544ed970b78e72f1739784417c146d5689d96ce79137"
} ],
"contactInfo" : {
"familyName" : "Cassini",
"fullName" : "Flavio Cassini",
"givenName" : "Flavio"
},
"organizations" : [ {
"name" : "DEVTECH .LLC",
"startDate" : "2015-03",
"title" : "President/Owner",
"current" : true
} ],
"demographics" : {
"locationDeduced" : {
"normalizedLocation" : "Boca Raton, United States",
"deducedLocation" : "Boca Raton, Florida, United States",
"city" : {
"name" : "Boca Raton"
},
"state" : {
"deduced" : true,
"name" : "Florida",
"code" : "FL"
},
"country" : {
"name" : "United States",
"code" : "US"
},
"continent" : {
"deduced" : true,
"name" : "North America"
},
"county" : {
"deduced" : true,
"name" : "Palm Beach"
},
"likelihood" : 1.0
},
"gender" : "Male",
"locationGeneral" : "Boca Raton, Florida, United States"
},
"socialProfiles" : [ {
"type" : "klout",
"typeId" : "klout",
"typeName" : "Klout",
"url" : "http://klout.com/DevTechServices",
"username" : "DevTechServices",
"id" : "91760869707035580"
}, {
"followers" : 67,
"following" : 67,
"type" : "linkedin",
"typeId" : "linkedin",
"typeName" : "LinkedIn",
"url" : "https://www.linkedin.com/in/devtechservices",
"username" : "devtechservices",
"id" : "428935547"
}, {
"bio" : "Student at Full Sail University",
"followers" : 5,
"following" : 36,
"type" : "twitter",
"typeId" : "twitter",
"typeName" : "Twitter",
"url" : "https://twitter.com/DevTechServices",
"username" : "DevTechServices",
"id" : "3245620291"
} ],
"digitalFootprint" : {
"scores" : [ {
"provider" : "klout",
"type" : "general",
"value" : 48
} ],
"topics" : [ {
"provider" : "klout",
"value" : "Bitcoin"
}, {
"provider" : "klout",
"value" : "Content Marketing"
}, {
"provider" : "klout",
"value" : "SAAS"
}, {
"provider" : "klout",
"value" : "Software"
}, {
"provider" : "klout",
"value" : "WordPress"
} ]
}
}

The short answer is that if $parsed_json represents an associative array of associative arrays, then it stands to reason that $parsed_json['photos'] is an associative array itself. To access the 'contactInfo' value inside it, you simply use $parsed_json['photos']['contactInfo'].

Related

Text search with Condition in Mongodb

I have below scenario where, I have one collection "demo" having all data which need to be search,
I have used text search,
{
"_id" : "1",
"type" : "Deal",
"description_title" : "New Deal for test",
"images" : "",
"start_date" : ISODate("2017-07-20T00:00:00.000+0000"),
"end_date" : ISODate("2017-10-30T11:59:00.000+0000"),
"status" : "1"
}
{
"_id" : "2",
"type" : "Event",
"description_title" : "Event1 test",
"images" : "",
"end_date" : ISODate("2017-10-20T00:00:00.000+0000")
"status" : "1"
}
{
"_id" : "3",
"type" : "Text",
"description_title" : "test",
"images" : "",
"status" : "1"
}
{
"_id" : "4",
"type" : "Event",
"description_title" : "Event2 test",
"images" : "",
"end_date" : ISODate("2017-07-20T00:00:00.000+0000")
"status" : "1"
}
In above collection I have stored all data which need to be search by using text search, But when "type" : "Event"/"Deal" then it should only return Active Deals & Events "Current date is less than end_date" need to be searched.
In above collection When I search for "Test", It should return,
{
"_id" : "1",
"type" : "Deal",
"description_title" : "New Deal for test",
"images" : "",
"start_date" : ISODate("2017-07-20T00:00:00.000+0000"),
"end_date" : ISODate("2017-10-30T11:59:00.000+0000"),
"status" : "1"
}
{
"_id" : "2",
"type" : "Event",
"description_title" : "Event1 test",
"images" : "",
"end_date" : ISODate("2017-10-20T00:00:00.000+0000")
"status" : "1"
}
{
"_id" : "3",
"type" : "Text",
"description_title" : "test",
"images" : "",
"status" : "1"
}
I have used below query, but it gives me all result,
db.demo.find({'$text' : {'$search' => 'test'},'$or' : {
{"type" : "Deal","end_date" : {'$gte' : ISODate("2017-09-14T11:59:00.000+0000") }},
{"type" : "Text"},
{"type" : "Event","end_date" : {'$gte' : ISODate("2017-09-14T11:59:00.000+0000") }},
}})
Above query return all records.
Please help me to achieve my result.

yii2 mongodb update embedded array

How to update members age whose name is TEST1 using yii2.?
Used below code to update , but i am specifying the indexes there , i want with out specifying the indexes.
User::updateAll([ '$set'=> ['Addresses.0.members.0.age'=>100] ],['IN','Addresses.members.name',['TEST1'] ]);
{
"_id" : ObjectId("595209b65312f48195fb2e01"),
"username" : "Test name",
"Addresses" : [
{
"address_no" : 1,
"Address" : "Test house",
"City" : "test city",
"State" : "Test state",
"Mobile" : "9999999",
"members" : [
{
"name" : "TEST1",
"age" : 35
},
{
"name" : "TEST2",
"age" : 30
},
]
},
{
"address_no" : 2,
"Address" : "2B, Test place",
"City" : "Test city",
"State" : "Test State",
"Pincode" : "12345",
"Phone" : "1234568789",
"Mobile" : 9999999999
}
],
"Beneficiaries" : [
{
"beneficiary_id" : 1,
"Name" : "Test1",
"Age" : "28",
"Sex" : "F"
}
],
"auth_key" : "esd8d89ds89ds89ds89ds",
}
there is position operator $ to do this kind of job
{
"Addresses.members.name" : "TEST2",
},
{
$set: {
"Addresses.$.members.0.age" : 40
}
}
Here I specified first index as it supports up to one level depth.
New feature might release in future to resolve this issue: https://jira.mongodb.org/browse/SERVER-831
Yii::$app->mongodb->getCollection('user')->update(['_id' => $id, 'members.name' => 'Test1'], ['$set' => [
'members.$.age' => 100,
]]);

Mongo Db aggregate $lookup returns empty array

when trying to "JOIN" operation with $lookup but results count is ok but "as" document is empty
I have two collections and i need to get user details from subscribercol with user_id in employer_jobscol
subscribercol
{
"_id" : ObjectId("58187e7551d244640626d7e1"),
"type" : "job_seeker",
"firstname" : "vishnu",
"lastname" : "kumar pv",
"email_array" : {
"primary" : "test#test.com",
"secondary" : "test#test.test",
"verified" : false
},
"address_array" : {
"address" : "test address22d",
"streetname" : "test222d",
"pincode" : "test222d",
"city" : "dddd",
"state" : "ALASKA2d",
"country" : "Argentinad"
},
"phone_array" : {
"primary" : "",
"secondary" : "",
"verified" : ""
},
"languages" : [
"english",
"malayalam",
"english2"
]
}
employer_jobscol
{
"_id" : ObjectId("582ada6b51d244073e2a7541"),
"employer_id" : ObjectId("58187e7551d244640626d7e1"),
"job_id" : "testjob16946",
"job_title" : "Test Job 25",
"category" : "IT",
"vacancies" : "5",
"salary" : "200000",
"location" : "Kollam",
"employer_name" : "test test",
"mobile" : "9123456987",
"video" : "",
"image" : "",
"work_place" : "option1",
"email" : "test#test.test",
"skills" : [
"php"
],
"isActive" : true,
"applied_users" : [
{
"user_id" : ObjectId("581b364751d2445c311cf6f1"),
"accepted" : false
},
{
"user_id" : ObjectId("58187e7551d244640626d7e1"),
"accepted" : false
}
]
}
my database query here, (executed with Robomongo )
db.getCollection('employer_jobscol').aggregate([ {
$unwind: "$applied_users"
},
{
$lookup:
{
from: "subscribercol",
localField: "user_id",
foreignField: "_id",
as: "subscribercol_docs"
}
}
])
Result is
{
"_id" : ObjectId("582ada6b51d244073e2a7541"),
"employer_id" : ObjectId("58187e7551d244640626d7e1"),
"job_id" : "testjob16946",
"job_title" : "Test Job 25",
"category" : "IT",
"vacancies" : "5",
"salary" : "200000",
"location" : "Kollam",
"employer_name" : "test test",
"mobile" : "9123456987",
"video" : "",
"image" : "",
"work_place" : "option1",
"email" : "test#test.test",
"skills" : [
"php"
],
"isActive" : true,
"applied_users" : {
"user_id" : ObjectId("58187e7551d244640626d7e1"),
"accepted" : false
},
"subscribercol_docs" : []
}
here subscribercol_docs is empty array i need user info (name, address etc..),
Because there is no user_id field in local document its "applied_users.user_id"
Try this
db.getCollection('employer_jobscol').aggregate([ {
$unwind: "$applied_users"
},
{
$lookup:
{
from: "subscribercol",
localField: "applied_users.user_id", // <-- check here
foreignField: "_id",
as: "subscribercol_docs"
}
}
])

How to get coordinates from the Query Autocomplete? [duplicate]

This question already has an answer here:
Places Autocomplete API to get GPS coordinates from address entered
(1 answer)
Closed 8 years ago.
Suppose a very simple function to query Query Autocomplete:
$query_google_places = function ($input, array $location = null) {
$parameters = ['key' => 'AIzaSyAjCY7qYiaMv8Kkk_-D1Ha7wlRkr5neppk', 'input' => $input, 'sensor' => 'false'];
if ($location) {
$parameters['location'] = $location['lat'] . ',' . $location['lng'];
$parameters['radius'] = 10000;
}
$url = 'https://maps.googleapis.com/maps/api/place/queryautocomplete/json?' . \http_build_query($parameters);
$response = file_get_contents($url);
return $response;
};
This returns:
{
"predictions" : [
{
"description" : "Pizza Hut, Halifax, United Kingdom",
"id" : "d9274717e1e203c41287fa5936701b9584814965",
"matched_substrings" : [
{
"length" : 9,
"offset" : 0
}
],
"reference" : "CmRaAAAAyulRkdspSJ2Mr5kmlhYOC-ZT7AsKdnnwjGkFFoGHNjMWwTS5mNvQBu6FqoQ89E4U0eC-PNGN0wPD8WEYgO1if6jMmxWAqkraDFOryC8B8cWTvX333l_0UaRv_sXBIITqEhCSrz9aQB0fch-AFDS3wKG7GhTRoQw09IODWJIorqjjwCYTktkfKw",
"terms" : [
{
"offset" : 0,
"value" : "Pizza Hut"
},
{
"offset" : 11,
"value" : "Halifax"
},
{
"offset" : 20,
"value" : "United Kingdom"
}
],
"types" : [ "establishment" ]
},
{
"description" : "Pizza Hut, John William Street, Huddersfield, United Kingdom",
"id" : "a1571b1434ac1491b5f6775d9a30f8ec7798a310",
"matched_substrings" : [
{
"length" : 9,
"offset" : 0
}
],
"reference" : "CoQBdAAAADaFqqtB9NGk_v1yZdY3m6OxILfLva556GBHxHIVdPHu_R0fQCm5kCduCjKL4BgiIdoNIejet3WI7xNanaiWDpiMD1Ml7Q9EnfhypReK0N6mQIY3TxOUcmf_INhkenU3ZVL8Vk9lAxqjq5ZfxiEZk9Vv8GaEnok_OJnaRBuZdCmtEhAYs-0Qc2Zza4fLuUXIiLknGhQogPaBcUm10Y59EA5i6BWPbTNXcA",
"terms" : [
{
"offset" : 0,
"value" : "Pizza Hut"
},
{
"offset" : 11,
"value" : "John William Street"
},
{
"offset" : 32,
"value" : "Huddersfield"
},
{
"offset" : 46,
"value" : "United Kingdom"
}
],
"types" : [ "establishment" ]
},
{
"description" : "pizza hut",
"matched_substrings" : [
{
"length" : 9,
"offset" : 0
}
],
"terms" : [
{
"offset" : 0,
"value" : "pizza hut"
}
]
},
{
"description" : "Pizza Hut Delivery, Wakefield Road, Huddersfield, United Kingdom",
"id" : "0c6830de14a8e23bf971626e880201f5290ec9a6",
"matched_substrings" : [
{
"length" : 9,
"offset" : 0
}
],
"reference" : "CoQBeQAAAJnMKHhJh-IE64z6seh3sbnm4dt0h1zbMYLr4BPGCITQTZLp4lkm12HKEFw0Bt761UaZPsESrY4ha7XSXusqqRVstmRFBF2wiwF5HGMO9DhRSeIzJ8CkNvsxmlqINosGBBPUHEDQEeSOoPHn3u3MeByoLVw6AzZ9N6eTrm94hsX9EhBB9cIoXjhHjR9Tr3zBROM7GhRhpYagW9qWs9hGZ3V0o9WXfrfcXw",
"terms" : [
{
"offset" : 0,
"value" : "Pizza Hut Delivery"
},
{
"offset" : 20,
"value" : "Wakefield Road"
},
{
"offset" : 36,
"value" : "Huddersfield"
},
{
"offset" : 50,
"value" : "United Kingdom"
}
],
"types" : [ "establishment" ]
},
{
"description" : "Pizza Hut Delivery, Westgate, Halifax, United Kingdom",
"id" : "667c14a2cb5bb676bd02911e924db82fb5cbe6df",
"matched_substrings" : [
{
"length" : 9,
"offset" : 0
}
],
"reference" : "CnRtAAAAEtMYQ9N4Gmn8dpZqzHOxYGPCNP9QQ6M-gHjj2hJv2euH4gUVvDhmgazi6LcRjdYpUF41moGLr26IGc2vOPfvFg_kHTqTIYHHwiD84bu0PeEzmLzIzJw2IkGNpcW1o6weO86TW8zaUaMFZ2zNW-tynhIQFT8GvSn_q7DAoP3ytM14ExoUN3sShljpfaCWEUknvsfAjZJ_Ru4",
"terms" : [
{
"offset" : 0,
"value" : "Pizza Hut Delivery"
},
{
"offset" : 20,
"value" : "Westgate"
},
{
"offset" : 30,
"value" : "Halifax"
},
{
"offset" : 39,
"value" : "United Kingdom"
}
],
"types" : [ "establishment" ]
}
],
"status" : "OK"
}
How do I get coordinates for each result? Note, that this is server-side question.
IMO, autocompletion or query autocompletion results live in a different world than search results. Google assumes you're not supposed to need coordinates in the autocompletion list because this is not the data you will be presenting on your map or in any controller. The data you'll present will be the result of a true "search" request.
Conclusion: you're supposed to call again Google server on endpoints such as nearby search, text search or details to get the coordinates.
If you want to use details, if the user clicked on a prediction from autocomplete for example, you'll use reference attribute as a parameter of your http request to identify the clicked prediction.

How to search a string in inner array using mongodb?

How to search value in multidimensional array,
for example I want to search example keyword in the following data in mongodb
I used to fetch all data from command
>db.info.find()
{
"_id" : ObjectId("4f74737cc3a51043d26f4b90"),
"id" : "12345",
"info" : [
{
"sno" : 1,
"name" : "ABC",
"email" : "abc#example.com"
},
{
"sno" : 2,
"name" : "XYZ",
"email" : "xyz#example.com"
},
{
"sno" : 3,
"name" : "XYZ",
"email" : "xyz#demo.com"
},
{
"sno" : 4,
"name" : "ABC",
"email" : "abc#demo.com"
},
{
"sno" : 5,
"name" : "Rohan",
"email" : "rohan#example.com"
}
]
}
Now, to find data having example I used command
>db.info.find({"info.email":"example"})
and it gives
{
"_id" : ObjectId("4f74737cc3a51043d26f4b90"),
"id" : "12345",
"info" : [
{
"sno" : 1,
"name" : "ABC",
"email" : "abc#example.com"
},
{
"sno" : 2,
"name" : "XYZ",
"email" : "xyz#example.com"
},
{
"sno" : 3,
"name" : "XYZ",
"email" : "xyz#demo.com"
},
{
"sno" : 4,
"name" : "ABC",
"email" : "abc#demo.com"
},
{
"sno" : 5,
"name" : "Rohan",
"email" : "rohan#example.com"
}
]
}
But I want only 3 out of 5 sub rows like
{
"_id" : ObjectId("4f74737cc3a51043d26f4b90"),
"id" : "12345",
"info" : [
{
"sno" : 1,
"name" : "ABC",
"email" : "abc#example.com"
},
{
"sno" : 2,
"name" : "XYZ",
"email" : "xyz#example.com"
},
{
"sno" : 5,
"name" : "Rohan",
"email" : "rohan#example.com"
}
]
}
Rohan, MongoDB always returns the whole document that you are searching on. You can't just make it return the array elements in which your keyword was found. If you want to do that, then you need to make sure all all embedded documents in the "info" field are in their own collection. And that might mean that you need to link them back to the original document in your "info" collection. Perhaps something like:
{
"sno" : 1,
"name" : "ABC",
"email" : "abc#example.com"
"info_id" : "12345",
},
Alternatively, you can of course do post-processing in PHP to obtain only the rows that you want.
Perhaps this is a good idea?
http://php.net/manual/en/class.mongoregex.php
I tried Map Reduce Function and it works on this type of problems the code is something like that:
Write a map function
map=function ()
{
filter = [];
this.info.forEach(function (s) {if (/example/.test(s.email)) {filter.push(s);}});
emit(this._id, {info:filter});
}
Write a reduce function
reduce=function(key, values) { return values;}
MapReduce Function
res=db.info.mapReduce(map,reduce,{out:{inline:1}})
And The Output look likes:
"results" : [
{
"_id" : ObjectId("4f9a2de0ea4a65c3ab85a9d3"),
"value" : {
"info" : [
{
"sno" : 1,
"name" : "ABC",
"email" : "abc#example.com"
},
{
"sno" : 2,
"name" : "XYZ",
"email" : "xyz#example.com"
},
{
"sno" : 5,
"name" : "Rohan",
"email" : "rohan#example.com"
}
]
}
}
],
"timeMillis" : 1,
"counts" : {
"input" : 3,
"emit" : 3,
"reduce" : 0,
"output" : 3
},
"ok" : 1,
Now you can find your search data from
printjson(res.results)
Did you try $ (projection)?
db.info.find({"info.email":"example"}, {"info.email.$":1})
document

Categories