How insert Multiple Array item into One Array in PHP - php

i want to add multiple Array item into One Array Object in PHP
i have array like below :
[
{
"name": "AAA"
},
{
"family": "BBB"
},
{
"job": "CCC"
}
]
And i need to Convert like below:
{
"name": "AAA",
"family": "BBB",
"job": "CCC"
}
Array Data maybe changed , but , i write this code for explain my problem :
$RetArray=array();
$Array_Test=array(array('name'=>'AAA'),array('family'=>'BBB'),array('job'=>'CCC'));
foreach ($Array_Test as $json_item){
foreach ($json_item as $key=>$value){
array_push($RetArray,array($key => $value));
}
}
echo json_encode($RetArray);
But this code returns the same as the first array!
I want to return every item into one array.

Try this:
$RetArray=[];
$SrcArray=[
["name"=>"AAA"],
["family"=>"BBB"],
["job"=>"CCC"],
];
foreach($SrcArray as $item){
$RetArray=array_merge($RetArray,$item);
}
echo json_encode($RetArray);
Here is what it got: https://3v4l.org/kZJ2T

you can use array_merge() or array_push()

Related

How to find specific key in JSON which I decoded into PHP? The key I want to find is repeated on multiple level of nesting

I want to target "KeyIwanttotarget" which is present on outside as well as nested.
The original file is JSON which I decoded into php using json_decode(). I want to target the specific key on all levels(external as well as nested) and store the value into another array e.g. using foreach and array_push.
"sample": [
{
"KeyIwanttotarget": "link",
"abc": "123",
"xyz": "123",
"pqr": "123",
"sample": [
{
"KeyIwanttotarget": "group",
"abc": "123",
"xyz": "123"
},
{
"KeyIwanttotarget": "link",
"abc": "123",
"xyz": "123",
"pqr": "123",
"sample": [
{
"KeyIwanttotarget": "link",
"abc": "123",
"xyz": "123",
"pqr": "123",
}
]
}
]
}
];
You need to be able to recursively check all of your key values. The best way to do that is with the array_walk_recursive() function.
This function allows you to use a callback function which will allow you to create some logic to compare your search string with the key names in the array to be searched.
The array_walk_recursive() passes two arguments through your callback function. The key and the key's value.
You will pass those arguments in through the function. You will compare the key name against your search string and if it matches you will add the key's value to the results array.
Like so:
$results = array();
$searchString = 'KeyIwanttotarget';
array_walk_recursive($array, function($value, $key) use (&$results, $searchString) {
if($key == $searchString){
$results[] = $value;
return $results;
}
});
print_r($results);
Hope it helps!

Laravel 5.4 array remove key index

In my controller, this statement generates an array:
// sort the region collection by continent for faster access in front end
$finalRegions = $regions->sortBy('continent_id');
{
"0":{
"id":1,
"name":"Alaska",
"image_x":227,
"image_y":117
},
"1":{
"id":5,
"name":"Australian Antartic Territory",
"image_x":1187,
"image_y":1037
....
}
}
How do I remove the index from the resulting object, so it looks like this:
[
{
"id":1,
"name":"Alaska",
"image_x":227,
"image_y":117
},
{
"id":5,
"name":"Australian Antartic Territory",
"image_x":1187,
"image_y":1037
....
}
]
This is stored in a field cast as json in the table class.
$res = [];
foreach ($finalRegions as $key => $value) {
$res[] = $value;
}
// $res contains desired result
Edit: Simple one liner (thanks to Jannie)
$res = array_values($finalRegions)
Since you have "Laravel" in your question title and it looks like you already have your regions in a Laravel Collection, there is an easier way. Just pipe your results through ->values() after the ->sortBy() clause like this:
$finalRegions = $regions->sortBy('continent_id')->values();
I still don't get why you need to remove those indexes, but you can do by this way.
<?php
$jsonArr = '{
"0":{
"id":1,
"name":"Alaska",
"image_x":227,
"image_y":117
},
"1":{
"id":5,
"name":"Australian Antartic Territory",
"image_x":1187,
"image_y":1037
}
}';
$decodeArr = json_decode($jsonArr, true);
print_r(json_encode($decodeArr));
This is just my idea, and you can edit part of your code where the query returns your JSON string.

Get whole array with keys and values where key equals value

I have arrays in my JSON like this:
[
{
"id":"bobbys_burgers",
"is_enabled":true,
"name":"Bobbys Burgers",
"supported_transactions":[
"222",
"111",
"333"
],
"enrollment_required":[
],
"restricted_transactions":[
"123"
]
},
{
"id":"randys_sandwich",
"is_enabled":true,
"name":"Randys Sandwich",
"supported_transactions":[
"321"
],
"enrollment_required":[
],
"restricted_transactions":[
]
},
]
I want to get all the keys of the whole array where id = randys_sandwich. for example, i want to search for id == randys_sandwich and return the is_enabled, name, supported_transactions, etc AND their values from that array. how can i do that in php?
You need to json_decode your array then loop through the objects in your array find the one with the id you're looking for.
$array = json_decode($json, true);
foreach ($item in $array) {
if ($item['id'] == 'randys_sandwich') {
var_dump($item);
break; // Once you've found the item no need to continue the loop
}
}

Looping through JSON fails with json_decode

I am pulling JSON data from a URL and attempting to display a list of just the display names.
In a way, this would be very easy too loop through if I knew that X amount of results would return each time. However, the results returned will vary from 0 to 50+.
I have done plenty of searches that all say "just use json_decode"... not so much the case.
I have the following JSON:
{
"ACK": "SUCCESS",
"ERROR": null,
"AGENT": {
"has_results": 1,
"agents": [
{
"display_name": "Alex",
"time_in_state": "5214",
"state": "Aux",
"callstakentoday": null,
"callsouttoday": null,
"agntpriority": null,
"skill_num": "76"
},
{
"display_name": "Bill",
"time_in_state": "6312",
"state": "Aux",
"callstakentoday": null,
"callsouttoday": null,
"agntpriority": null,
"skill_num": "76"
},
{
"display_name": "Carrie",
"time_in_state": "5982",
"state": "Aux",
"callstakentoday": null,
"callsouttoday": null,
"agntpriority": null,
"skill_num": "76"
},
{
"display_name": "David",
"time_in_state": "4226",
"state": "Aux",
"callstakentoday": null,
"callsouttoday": null,
"agntpriority": null,
"skill_num": "76"
}
]
},
"SKILL": {
"has_results": 1,
"num_skills": 1,
"skills": [
{
"display_name": "Phone Skills",
"skill_num": "76",
"callsinqueue": "0",
"callstoday": "9",
"abandtoday": "0",
"lwt": "0",
"ewt": "0",
"servicelvl": "100",
"avgspeedans": "6",
"talktime": "289"
}
]
},
"TIME": 1383766541
}
From the examples and documentation I have read, the following code has been created:
<?php
$url="http://myjsonurl.local";
$json = file_get_contents($url);
//echo $json;
$json = json_decode($json);
foreach($json as $item->display_name)
{
echo $item->agents->display_name;
}
?>
My end goal is to have a list of only names which I can then display in an alternate webpage.
So my question is... how do I read this page and format the data nicely (perhaps an array I can just print?) so I can utilize it in the future?
You have the following in your code:
foreach($json as $item->display_name)
This is incorrect and doesn't do what you want. As you can see by doing a print_r($json), the names are in $json->AGENT->agents, so you'll want to loop through those items and then traverse the display_name using arrow syntax ($item->display_name). Once you have the display name, you can push it into an array, and use it however you want.
Your loop should look like below:
$names = array(); // initialize empty array
foreach($json->AGENT->agents as $item)
{
$names[] = $item->display_name;
}
print_r($names); // see the array contents
Output:
Array
(
[0] => Alex
[1] => Bill
[2] => Carrie
[3] => David
)
Demo.
Note: If you don't know the structure of the JSON object beforehand, then you can use a nested foreach loop to retrieve the names.
The array you want to iterate is $json->AGENT->agents. Also, your foreach syntax is wrong.
Try:
foreach($json->AGENT->agents as $item)
{
echo $item->display_name;
}
If you want to get the JSON data as an array rather then an object, use json_decode($json, true) instead. This tells the function to return it as an associative array, as you can read here: http://php.net/manual/en/function.json-decode.php
You have an error in your foreach loop.
foreach($json as $item->display_name)
{
echo $item->agents->display_name;
}
$item is not an object and you are actually trying in this line to access property "display_name" of none object ($item)
foreach($json as $item)

Comparing JSON arrays by a specific key in PHP

I want to use the data from array A (below), but only when the item ID from array A does NOT match an ID from items in array B (also, below). How would I go about comparing these two JSON array's by the key of ID (from items) via PHP? I imagine I first need to convert them with json_decode, but I'm not sure where to go after that?
Please note that array B has more nests ("items", "something", & "posts"), unlike array A. I want to compare the ID from items, not posts.
Array A:
{
"data": [{
"category": "Games",
"id": "45345"
},
{
"category": "Music",
"id": "345345345"
},
{
"category": "Food",
"id": "1"
},
{
"category": "Pets",
"id": "13245345"
}]
}
Array B:
{
"data": {
"something": "blah",
"posts": [{
"id": "34241",
"title": "orange"
}],
"items": [{
"id": "1",
"name": "orange"
},
{
"id": "2",
"name": "dog"
},
{
"id": "3",
"name": "cat"
},
{
"id": "4",
"name": "apple"
}]
}
}
With the case above, it would run through array A and output everything from array A except for the third item, since the id of that item (1) matches one of the id's in array B items.
Based on my understanding, you need a two step process. The first is extracting the ids from the first JSON blob, and the second is filtering the second JSON blob. So basically, we have map and filter. And it just so happens we can use PHP's inbuilt functions for this:
$ids = array_map(
function($value) {
return $value['id'];
},
$array2['data']['items']
);
First, we flatten the second array's items element into the individual ids. We "map" over the data.items array, and return the $id attribute of each array. Now, we have an array of ids...
$new = array_filter(
$array1['data'],
function($var) use ($ids) {
return !in_array($var['id'], $ids);
}
);
Now, we use that to filter the first blobs array to determine if an element is new or not. So we use array filter to handle it for us. All we need to do is check the $ids array to see if the current data's id is there (and if it is, throw it away). So we want to filter the array to be only variables that are not in array of $ids (hence !in_array($var['id'], $ids)...)
Decode the items into PHP arrays. Use a SPL like array_diff() to get the results of a diff comparison.
Referances to get you started:
http://www.php.net/manual/en/function.array-diff.php
http://php.net/manual/en/function.array-diff-key.php
http://www.php.net/manual/en/function.json-decode.php
Should be about what your looking for

Categories