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;
};
Related
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;
}
}
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;
}
}
}
}
}
}
}
}
}
Hi i wonder how i can delete data from json file based on id if my json struct looks like that:
[
{
"id": 1,
"title": "a",
"decription": "b"
},
{
"id": 2,
"title": "c",
"decription": "d"
}
]
What I've tried so far:
if (isset($_POST['delete_post']))
{
$id = $_POST['post-id'];
if(empty($id)) return;
$posts = json_decode(file_get_contents('posts.json'));
foreach ($posts as $post)
{
if ($post->id == $id)
{
unset ($post);
}
$save = json_encode($posts, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
file_put_contents('posts.json', $save);
}
}
And i literally stuck at this ponint.
unset $post doesn't remove the element from the array, it just unsets that temporary variable.
After unsetting the element you need to use array_values() to get a new array with consecutive indexes. If there's a gap in the indexes, json_encode() will encode it as an object.
You also should break out of the loop once you find the element to delete and rewrite the file.
foreach ($posts as $i => $post)
{
if ($post->id == $id)
{
unset ($posts[$i]);
$save = json_encode(array_values($posts), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
file_put_contents('posts.json', $save);
break;
}
}
It seems your unset is not working because you don't pass $post it by reference.
I would do it with array_filter tho.
function deleteById($json, $id) {
return json_encode(array_filter(json_decode($json, true),
function($e) use ($id) {
return $e['id'] != $id;
}
));
}
There's and array_filter function in php, which is perfect for your case.
// ...
$posts = array_filter($posts, function($item) use ($id) {
return $item != $id;
});
// ...
Btw. your code don't work, because you unset only the current loop var and not the actual array item. If you pass an key to the foreach, you could also delete the actual array item.
foreach ($posts as $key => $post) {
if ($post->id == $id) {
unset($posts[$key]);
}
}
// save json
Little issue, how to correct check JSON, recieved with GET by codeception.
Here it come..
{
"brands":[
{
"letter":"b",
"list":[
{
"text_ident":"brand1",
"title":"brand1",
"shortDescription":"brand1brand1"
},
{
"text_ident":"brand2",
"title":"brand2",
"shortDescription":"brand2brand2"
},
{
"text_ident":"brand3",
"title":"brand3",
"shortDescription":"brand3brand3"
}
]
},
{
"letter":"v",
"list":[
{
"text_ident":"vrand3",
"title":"vrand3",
"shortDescription":"vrand3vrand3"
}
]
}
]
}
And here is the BrandsMenuCept.php test
I start it with...
$fix = new app\tests\api\v1\fixtures\BrandsFixture();
$fix->load();
$I = new ApiTester($scenario);
$I->wantTo('test GET v1/brands/menu');
$I->sendGet('http://example.com/v1/brands/menu');
$I->seeResponseCodeIs('200');
$I->seeResponseIsJson();
$I->seeResponseJsonMatchesJsonPath('$.brands');
...
And what i should write after, how to check multiple arrays?
You can do this way:
First json_decode the response with true parameter like this
$responsearr=json_decode($json, true);
Then you can check the count of the array like this:
if(count($responsearr)>0){
//logic follows here...
}else{
//invalid json message comes here
}
I have one array having multiple objects (say 3 Objects), each having 3 "Key-Value" pairs.
$PredefinedResult is something like this :
[
{
"EffectiveStatusId":0,
"EffectiveStatus":"abc",
"RecordCount":0
},
{
"EffectiveStatusId":0,
"EffectiveStatus":"def",
"RecordCount":0
},
{
"EffectiveStatusId":0,
"EffectiveStatus":"ghi",
"RecordCount":0
}
]
I have another array of objects named $MainResult with values like :
[
{
"EffectiveStatusId":1,
"EffectiveStatus":"abc",
"RecordCount":7
},
{
"EffectiveStatusId":6,
"EffectiveStatus":"def",
"RecordCount":91
}
]
Expected Result :
I want to replace the similar objects inside $PredefinedResult with the objects from $MainResult and want result like this :
[
{
"EffectiveStatusId":1,
"EffectiveStatus":"abc",
"RecordCount":7
},
{
"EffectiveStatusId":6,
"EffectiveStatus":"def",
"RecordCount":91
},
{
"EffectiveStatusId":0,
"EffectiveStatus":"ghi",
"RecordCount":0
}
]
What I tried :
I tried with this code but it's not giving me the desired result.
$FinalResult = array_replace($PredefineResult,$MainResult);
Can anyone help me on how to get the Expected Result as mentioned above ?
There's no "built-in" function for this. You're gonna have to loop and compare each manually. array_map seems like an OK choice here:
$PredefinedResult = array_map(function($a) use($MainResult){
foreach($MainResult as $data){
if($a->EffectiveStatus === $data->EffectiveStatus){
return $data;
}
}
return $a;
}, $PredefinedResult);
DEMO: http://codepad.viper-7.com/OHBQK8
Iterate through the array and manual compare the values as follows.
$res = array();
foreach ($PredefineResult as $result){
foreach ($MainResult as $mresult){
if(($result->EffectiveStatus == $mresult->EffectiveStatus) && $mresult->RecordCount!=0){
$res[] = $mresult;
}else $res[] = $result;
}
}
print_r($res);