how to filter JSON data rows - php

I want to show data that include in specified categories. but the white page is my result
the function should search in json to display the rows that contain in specified categories.
for example: i need to display the users that contain cat 1 and cat 2 .
the result should list all name in rows that contain the specified category like this:
Steve
Stafin
Sara
if you needed any other question or problem in my describe, just tell me to let you know.
I appreciate your tips
users.json:
{"data":[
{
"id":1,
"category_name":"Writers",
"users":{
"data":[
{
"name":"Steve",
"id":"1",
"cat":"1",
"description":{
"data":[
{
"instagram":"steveid"
}
]
}
},{
"name":"Stafin",
"id":"2",
"cat":"2",
"description":{
"data":[
{
"instagram":"stafinid"
}
]
}
},{
"name":"Jack",
"id":"3",
"cat":"3",
"description":{
"data":[
{
"instagram":"jackid"
}
]
}
},{
"name":"Sara",
"id":"3",
"cat":"2",
"description":{
"data":[
{
"instagram":"saraid"
}
]
}
}
]
}
}
]}
php:
$str = file_get_contents('http://localhost/json/users.json');
$json = json_decode($str, true);
function searchArray($searchkey, $searchval, $array) {
foreach ($array as $key => $val) {
if ($val[$searchkey] === $searchval) {
return $val;
}
}
return null;
}
//i didn't know how to describe users for each time in 'do while'
$user = searchArray('id', '3', $json['data'][0]['users']['data']);
$cat = ["1", "3"];
if (in_array($user['cat'], $cat)) {
echo $user['description']['data'][0]['instagram'];
}
the users.json is the json data

This //i didn't know how to describe users for each time in 'do while' is the root of the problem, because you cannot know unless program crawls the array and finds all the id's before it even starts looking for the cats.
This snippet will give the answer to the specific problem in this question.
foreach ($json['data'][0]['users']['data'] as $row) {
if (in_array($row['cat'],[1,2])) {
echo $row['name'],"\n";
}
}
It is unclear what other "queries" the function will need to answer. I leave it to you to construct a function that will handle the necessary cases.

Related

PHP function not returning any information when passed via return, but will happily echo within the function

I'm wondering if someone could help me out with a function I'm writing. Basically I'm trying to search through some JSON-LD data for a specific key. The JSON-LD data has been assigned to an array using json_decode. The array looks like this but could have a different format and structure:
{
"#context":"https://schema.org",
"#graph":[
{
"#type":"Organization",
"#id":"https://www.web.site/#organization",
"name":"Some Name",
"url":"https://www.web.site/",
"sameAs":[
"https://www.facebook.com/website",
"https://www.linkedin.com/company/website",
"https://twitter.com/website"
],
"logo":{
"#type":"ImageObject",
"#id":"https://www.web.site/#logo",
"inLanguage":"en",
"url":"https://web.site/logo.svg",
"width":200,
"height":100,
"caption":"Some Name"
},
"image":{
"#id":"https://www.web.site/#logo"
}
},
{
"#type":"WebSite",
"#id":"https://www.web.site/#website",
"url":"https://www.web.site/",
"name":"Some Name",
"inLanguage":"en",
"description":"Some description here.",
"publisher":{
"#id":"https://www.web.site/#organization"
},
"potentialAction":[
{
"#type":"SearchAction",
"target":"https://www.web.site/?s={search_term_string}",
"query-input":"required name=search_term_string"
}
]
},
{
"#type":"WebPage",
"#id":"https://www.web.site/#webpage",
"url":"https://www.web.site/",
"name":"Some Name",
"isPartOf":{
"#id":"https://www.web.site/#website"
},
"inLanguage":"en",
"about":{
"#id":"https://www.web.site/#organization"
},
"datePublished":"2017-01-01T21:21:21+00:00",
"dateModified":"2017-01-01T21:21:21+00:00",
"description":"Some description here.",
"potentialAction":[
{
"#type":"ReadAction",
"target":[
"https://www.web.site/"
]
}
]
}
]
}
The function I have written to find a key looks like this:
function findArrayKey($array, $find) {
foreach($array as $key => $value) {
if (is_array($value)) {
if((string)$key == $find){
foreach($value as $key => $value) {
$info .= $value;
}
} else {
findArrayKey($value,$find);
}
}
}
echo $info; // prints the info
return $info; // returns nothing
}
echo findArrayKey($myarray,$keyimlookingfor);
The echo findArrayKey line at the bottom just does nothing (I've also tried var_dump and print_r and still get nothing) yet the echo within the function works perfectly.
The output from the echo within the function is:
https://www.facebook.com/websitehttps://www.linkedin.com/company/websitehttps://twitter.com/website
The output from the echo outside it (with the data passed back via return) is blank..
Any help someone could provide would be greatly appreciated, thank you for everything in advance.

how to search in Json and get sub data [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 3 years ago.
i have a json file of users with all descriptions and its hard to find them with data[2]. imagine in data[0]->users->data i have 3 user and i want to find name = "Stafin" to get description->data->instagram and get value. i'll give you a simple json data
{"data":[
{
"id":1,
"category_name":"Writers",
"users":{
"data":[{
"name":"Steve",
"id":"1",
"description":{
"data":[
{
"instagram":"steveid"
}
]
}
},{
"name":"Stafin",
"id":"2",
"description":{
"data":[
{
"instagram":"stafinid"
}
]
}
},{
"name":"Sara",
"id":"3",
"description":{
"data":[
{
"instagram":"saraid"
}
]
}
}]
}
}
]}
Code:
<?php
$str = file_get_contents('http://localhost/json/test.json');
$json = json_decode($str, true);
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['id'] === $id) {
return $key;
}
}
return null;
}
$id = searchForId('2', $json);
echo $id;
?>
note that: answer it in php language
sorry for my bad English language. if you didn't get that, just tell me to describe more
Your function searches for id, but you said you wanted to search for name. You can make the key another parameter of the function. Then you can use it to find the id in the data array, and the name in the users['data'] array.
function searchArray($searchkey, $searchval, $array) {
foreach ($array as $key => $val) {
if ($val[$searchkey] === $searchval) {
return $val;
}
}
return null;
}
foreach ($json['data'] as $data) {
$user = searchArray('name', 'Stafin', $data['users']['data']);
if ($user) {
echo "Found Stafin";
foreach ($user['description']['data'] as $desc) {
if (isset($desc['instagram'])) {
echo ", Instagram is {$desc['instagram']}";
break;
}
}
break;
}
}

How to find json direct parent based on children value

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

Loop json object as array in PHP

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

How to get json format for monogo db object [duplicate]

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"
}
]

Categories