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

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

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 filter JSON data rows

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.

Integrating mailchimp with CRM

Need to get campaign_id with the list_id that I've got. My goal is to get all the campaign data and then sort out using the list_id. I have been able to retrieve the campaign response body, but somehow failing to get the campaign list_id. Any help or a different approach would be appreciated. Sharing my code and mailchimp api related reference.
MailChimp api ref:
"campaigns": [
{
"id": "42694e9e57",
"type": "regular",
"create_time": "2015-09-15T14:40:36+00:00",
"archive_url": "http://",
"status": "save",
"emails_sent": 0,
"send_time": "",
"content_type": "template",
"recipients": {
"list_id": "57afe96172", // this is required
"segment_text": ""
},
My Progress:
public static function getCampaignID($list_id){
$MCcampaigninfo = self::$mc_api->get("/campaigns"); // gives a response consisting 3 rows, required value is in 1st row, which is an array
foreach ($MCcampaigninfo as $key => $value) {
if ($value[8]->'list_id' == $list_id) { //under the 'campaign'array, we need the 9th position property 'recipient'
$campaign_id = $value[12]->'id';
}
}
}
This code assumes the response of $mc_api->get is equal to the JSON you showed in your example
public static function getCampaignID($list_id) {
$campaigns = json_encode(self::$mc_api->get("/campaigns"), true);
$campaignIds = [];
foreach ($campaigns as $campaign) {
//if the list_id matches the current campaign recipients['list_id'] add to the array
if ($campaign['recipients']['list_id'] === $list_id) {
$campaignIds[] = $campaign['id'];
}
}
//return an array with campaignIds
return $campaignIds;
}
Got it working. The api structure seems different in reality from their documentation. Thanks for all the help. Posting my updated code.
public static function getCampaignID($list_id){
$MCcampaigninfo = self::$mc_api->get("/campaigns");
foreach ($MCcampaigninfo as $key => $campaign) {
if($key == campaigns){
foreach ($campaign as $key2 => $clist) {
foreach ($clist as $key3 => $recip) {
if($key3 == id){
$campaign_id = $recip;
}
elseif($key3 == recipients){
foreach($recip as $key4 => $listid){
if($key4 == list_id){
if($listid == $list_id){
return $campaign_id;
}
}
}
}
}
}
}
}
}

php | dynamic api call

I am trying to create a dynamic endpoint for a API I am creating in order to include some data but only if it is required so I can use it in multiple places.
The idea is to have api.domain.com/vehicle to bring back basic vehicle information but if I did api.domain.com/vehicle?with=owners,history then the idea is to have a function which maps the owners and history to a class which will return data but only if it is required.
This is what I currently have.
public static function vehicle()
{
$with = isset($_GET['with']) ? $_GET['with'] : null;
$properties = explode(',', $with);
$result = ['vehicle' => Vehicle::data($id)];
foreach ($properties as $property) {
array_push($result, static::getPropertyResponse($property));
}
echo json_encode($result);
}
Which will then call this function.
protected static function getPropertyResponse($property)
{
$propertyMap = [
'owners' => Vehicle::owner($id),
'history' => Vehicle::history($id)
];
if (array_key_exists($property, $propertyMap)) {
return $propertyMap[$property];
}
return null;
}
However, the response I'm getting is being nested within a index, which I don't want it to be. The format I want is...
{
"vehicle": {
"make": "vehicle make"
},
"owners": {
"name": "owner name"
},
"history": {
"year": "26/01/2018"
}
}
But the format I am getting is this...
{
"vehicle": {
"make": "vehicle make"
},
"0": {
"owners": {
"name": "owner name"
}
},
"1": {
"history": {
"year": "26/01/2018"
}
}
}
How would I do this so it doesn't return with the index?
Vehicle::history($id) seems to return ['history'=>['year' => '26/01/2018']], ...etc.
foreach ($properties as $property) {
$out = static::getPropertyResponse($property) ;
$result[$property] = $out[$property] ;
}
Or your methods should returns something like ['year' => '26/01/2018'] and use :
foreach ($properties as $property) {
$result[$property] = static::getPropertyResponse($property) ;
}

PHP Search JSON File and get result

Here is my JSON File that contains my items. I would like to search for the item name and return the id.
CODE:
$jsonitem = file_get_contents("data.json");
$objitems = json_decode($jsonitem);
$findById = function($id) use ($objname) {
foreach (json_decode($objname) as $friend) {
if ($friend->id === $id) return $friend->name;
}
return;
};
echo $findById('6') ?: 'No record found.';
JSON FILE:
[
{
"id":1,
"name":"Candy Wrapper",
"value":500,
},
{
"id":2,
"name":"Torch",
"value":2000,
}
]
Your logic is correct, but you have a couple of errors in your code:
You are referencing $objname, which is not set
You are decoding the data twice
As #Mikey pointed out, your JSON is invalid because of trailing commas on the "values" lines.
Try:
$findById = function($id) use ($objitems) {
foreach ($objitems as $friend) {
if ($friend->id == $id) return $friend->name;
}
return false;
};

Categories