Hi guys I was wonder how you can return the index based on ID with the following.
$friends = '{
"data": [
{
"name": "Paul",
"id": "12000"
},
{
"name": "Bonnie",
"id": "120310"
},
{
"name": "Melissa",
"id": "120944"
},
{
"name": "Simon",
"id": "125930"
},
{
"name": "Anthony",
"id": "120605"
},
{
"name": "David",
"id": "120733"
}
]
}';
$obj = json_decode($friends);
for example, I want to get print the name based on ID. I've had a go at using array_search but it didn't like the structure of the array. I will be using it inside a sql loop and passing the ID from the query to return the name string from the array.
print $obj->{'data'}[0]->{'name'};
//where 0 is returned index based on a defined ID.
thanks a lot
The json_decode makes your variables into objects. To do a search, you could use:
// The extra true at the end makes it decode to associative arrays
$json = json_decode($friends, true);
findByName($json, 1234);
function findNameById($obj, $id) {
foreach($obj as $o) {
if($o['id'] == $id) return $o['name'];
}
return false;
}
You will need PHP 5.3 in order to utilize the following closure and enhanced ternary operator (prints name if record is found; otherwise, prints 'No record found.'):
$findById = function($id) use ($friends) {
foreach (json_decode($friends)->data as $friend) {
if ($friend->id === $id) return $friend->name;
}
return;
};
echo $findById('125930') ?: 'No record found.';
Nice thing about this is that you can pass this callable around and it will remember the scope it was defined with. This means that you can pass any ID but the $friends array will always be available to the closure.
Related
I've got the following data structure:
Array -> Object -> Array -> Object -> Object
[
{
"id":6834,
"contract_id":13,
"schedule_column_values":[
{
"id":34001,
"field_value":{
"id":324241,
"value":10,
"field":{
"id":1,
"signature":"ios"
}
}
},
{
"id":34001,
"field_value":{
"id":324241,
"value":10,
"field":{
"id":1,
"signature":"android"
}
}
}
]
}
]
What I'm trying to achieve is that if a field has the signature of "android", remove its grandparent object from schedule_column_values. Basically, if a signature is "android", the final data would look like this:
[
{
"id": 6834,
"contract_id": 13,
"schedule_column_values": [
{
"id": 34001,
"field_value": {
"id": 324241,
"value": 10,
"field": {
"id": 1,
"signature": "ios"
}
}
}
]
}
]
This is just an example but the structure is always the same and we always know what signature we're looking for. It could be anything other than android but we know the string we're looking for.
I've tried a nested foreach loop and tried unset but it doesn't seem to work. The other way is I've set a NULL to object value of schedule_column_values when the signature of field is matched, but I cannot have NULL in the object.
What would be a good way to filter out this structure?
This is a perfect use case for array_filter:
$filtered_array = [];
foreach($array as $grandparent){
$filtered_schedules = array_filter(
$grandparent->schedule_column_values,
function($item){
return $item->field_value->field->signature !== 'android';
}
);
$altered_grandparent = clone $grandparent;
$altered_grandparent->schedule_column_values = $filtered_schedules;
$filtered_array[] = $altered_grandparent;
}
I need to find the direct parent of all instance of "type": "featured-product" in a JSON file using PHP. store this parent string in a variable. use a foreach.
In the example below, the variable would have the value "1561093167965" and "3465786822452"
I'm a little lost, thank you for the help!
{
"current": {
"sections": {
"1561093167965": {
"type": "featured-product"
},
"3465786822452": {
"type": "featured-product"
}
}
}
}
foreach ($json['current']['sections'] as $sectionName => $section) {
if ($section['type'] && $section['type'] == 'featured-product') {
$featuredId = $sectionName;
}
}
Another approach you can take is to create a new array containing only featured-products using array_filter and then extract the keys. From the docs:
If the callback function returns TRUE, the current value from array is
returned into the result array. Array keys are preserved.
$product_sections = array_keys(
array_filter($json['current']['sections'], function($val) {
return $val['type'] === 'featured-product';
}));
Demo
The problem in your original code is that your $featuredId variable is getting overwritten in each iteration of the loop, so when it ends its value will be the one of last element processed. If you have to deal with multiple values, you'll have to add it to an array or do the work directly inside the foreach. You can see the other answers for how to fix your code.
There is probably a cleaner way but this works using json_decode and iterating over the array with foreach
$json='{
"current": {
"sections": {
"1561093167965": {
"type": "featured-product"
},
"3465786822452": {
"type": "featured-product"
}
}
}
}';
$e=json_decode($json,true);
foreach($e['current']['sections'] as $id=>$a){
if($a['type']=='featured-product'){
echo 'the parent id is '.$id;
}
}
//change this with the real json
$json='{
"current": {
"sections": {
"1561093167965": {
"type": "featured-product"
},
"3465786822452": {
"type": "featured-product"
}
}
}
}';
$result = [];
$jsond=json_decode($json,true);
foreach($jsond['current']['sections'] as $k=>$v){
if($v['type']=='featured-product'){
$result[] = $k;
}
}
How can i loop the response to get all ids and names?
If the response like this:
{
"Data": [
{
"Id": "4321",
"Name": "Dog"
},
{
"Id": "749869",
"Name": "Cat"
}
]
}
I can get all the ids and names using this code:
foreach (json_decode($response->content)->Data as $resp) {
echo $resp->Id;
echo $resp->Name;
}
But, if the response like this:
{
"Data": {
"dog": {
"Id": "4321",
"Name": "Dog"
},
"cat": {
"Id": "749869",
"Name": "Cat"
}
}
}
How can i get all the ids and names without knowing the amount of the array? Thank you.
You can get PHP to read everything into an (associative where applicable) array.
foreach (json_decode($response->content, true)["Data"] as $resp) { //2nd parameter is to decode as array
echo $resp["Id"];
echo $resp["Name"];
}
Example run: https://eval.in/954621
Alternatively you can do the lazy thing and just cast:
foreach ((array)json_decode($response->content)->Data as $resp) {
echo $resp->Id;
echo $resp->Name;
}
Well if you want to extract all ids into one array (I assume you mean all into one array), to use in a database query as an example. I would recommend you doing like this.
$ids = array_values(array_map(function($animal){
return intval($animal['Id']);
}, json_decode($response->content, true)['Data']));
var_dump($ids);
you do the same ! foreach loop would work on both.
the json response supposed to have the same format every time, unless you have a really weird API.
<?php
$response = json_decode($json);
foreach($response as $animal => $data)
{
echo $animal;
echo $data->id;
echo $data->name;
}
I am using PHP to connect with MongoDB. My code is as follows.
// connect
$m = new MongoClient($con_string); // connect to a remote host at a given port
$db = $m->main;
$customers = $db->customer->find();
i want to return $customers collection as json document to my HTML. How can i do this?
You can do this two ways:
echo json_encode(iterator_to_array($customers));
or you can manually scroll through it:
foreach($customers as $k => $row){
echo json_encode($row);
}
Each of MongoDBs objects should have their __toString() methods correctly implemented to bring back the representation of the value.
This also will work. And you can customize your json as well.
$arr = array();
foreach($customers as $c)
{
$temp = array("name" => $c["name"], "phone" => $c["phone"],
"address" => $c["address"]);
array_push($arr, $temp);
}
echo json_encode($arr);
Other answers work, but it is good to know that the generated JSON will have the following form (in this example I use an hypothetical "name" field for your customers):
{
"5587d2c3cd8348455b26feab": {
"_id": {
"$id": "5587d2c3cd8348455b26feab"
},
"name": "Robert"
},
"5587d2c3cd8348455b26feac": {
"_id": {
"$id": "5587d2c3cd8348455b26feac"
},
"name": "John"
}
}
So in case you don't want the Object _id to be the key of each of your result objects you can add a false parameter to iterator_to_array.
Your code would be:
echo json_encode(iterator_to_array($customers, false), true);
This creates the same result as
$result = Array();
foreach ($customers as $entry) {
array_push($result, $entry);
}
echo json_encode($result, true);
which is an array of JSON objects
[
{
"_id": {
"$id": "5587d2c3cd8348455b26feab"
},
"name": "Robert"
},
{
"_id": {
"$id": "5587d2c3cd8348455b26feac"
},
"name": "John"
}
]
I need to iterate over objects in PHP and to apply a certain function on each and every single value in this object.
The objects are absolutely arbitrary. They can include vars, another objects, arrays, arrays of objects and so on...
Is there a generic method to do so? If yes, how?
Usage example:
RESTful API which receives requests in JSON format.
json_decode() is executed on request body and creates an arbitrary object.
Now, it is good, for example, to execute mysqli_real_escape_string() on every value in this object before further validations.
OBJECT EXAMPLE:
{
"_id": "551a78c500eed4fa853870fc",
"index": 0,
"guid": "f35a0b22-05b3-4f07-a3b5-1a319a663200",
"isActive": false,
"balance": "$3,312.76",
"age": 33,
"name": "Wolf Oconnor",
"gender": "male",
"company": "CHORIZON",
"email": "wolfoconnor#chorizon.com",
"phone": "+1 (958) 479-2837",
"address": "696 Moore Street, Coaldale, Kansas, 9597",
"registered": "2015-01-20T03:39:28 -02:00",
"latitude": 15.764928,
"longitude": -125.084813,
"tags": [
"id",
"nulla",
"tempor",
"do",
"nulla",
"laboris",
"consequat"
],
"friends": [
{
"id": 0,
"name": "Casey Dominguez"
},
{
"id": 1,
"name": "Morton Rich"
},
{
"id": 2,
"name": "Marla Parsons"
}
],
"greeting": "Hello, Wolf Oconnor! You have 3 unread messages."
}
If you just need to walk over the data and won't need to re-encode it, json_decode()'s second parameter, $assoc will cause it to return an associative array. From there, array_walk_recursive() should work well for what you're after.
$data = json_decode($source_object);
$success = array_walk_recursive($data, "my_validate");
function my_validate($value, $key){
//Do validation.
}
function RecursiveStuff($value, $callable)
{
if (is_array($value) || is_object($value))
{
foreach (&$prop in $value) {
$prop = RecursiveStuff($prop);
}
}
else {
$value = call_user_func($callable, $value);
}
return $value;
}
And use it like:
$decodedObject = RecursiveStuff($decodedObject, function($value)
{
return escapesomething($value); // do something with value here
});
You can just pass function name like:
$decodedObject = RecursiveStuff($decodedObject, 'mysqli_real_escape_string');