Get whole array with keys and values where key equals value - php

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

Related

How insert Multiple Array item into One Array in 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()

Laravel - Map Eloquent collection using a value as key, pushing an array into the keys

I have a model that has a query, that returns the next eloquent collection.
Illuminate\Database\Eloquent\Collection {#4431
all: [
App\Models\ProductVariation {#4429
attribute_value_id: 48,
name: "Storlek",
value: "Small",
},
App\Models\ProductVariation {#4438
attribute_value_id: 41,
name: "Storlek",
value: "Medium",
},
App\Models\ProductVariation {#4439
attribute_value_id: 34,
name: "Storlek",
value: "Large",
},
App\Models\ProductVariation {#4440
attribute_value_id: 70,
name: "Color",
value: "Green",
},
],
}
I need to map this collection into Array, keyed by "name"
[
"Storlek" => [...]
"Color" => [...]
]
I try with KeyBy, groupBy, and mapWithKeys, with those methods, it keeps only the last element into the array
The solution that I find is the next:
$map = [];
foreach($variations as $value)
{
$key = $value["name"];
if(!isset($map[$key]))
$map[$key] = [];
$map[$key][] = $value;
}
return $map;
Is that the only solution? is there any other best solution?
EDIT:
I use the ->toArray() method to iterate the collection
You are looking for the groupBy (https://laravel.com/docs/8.x/collections#method-groupby) method.
$mapped = $variations->groupBy(function($item){
return $item->name;
});
dd($mapped->toArray());
This will return your data grouped by the name.
Also, if you only want to return the value (and not the whole ProductVariation), you could also remap the grouped Collection:
$mapped = $variations->groupBy(function($item){
return $item->name;
})->map(function($group){
return $group->map(function($item){
return $item->value;
});
});
dd($mapped->toArray());

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.

Re-looping through an array (PHP)

I have a strange array. I get some objects that have children, and then I have some objects that are the id's of the children.
array {
"1": {
"children": [
10,
11,
],
"parent_id": null,
}
}
"2": {
"children": [
12,
13,
]
"parent_id": null,
}
"10": {
"name": Tom,
"parentid": 1,
}
"11": {
"name": Peter,
"parentid": 1,
}
}
I'm trying to first list out the objects if they have children via a foreach.
foreach ($array as $key) {
if (parent_id === null){
echo id;
}
}
So I get a list that looks like this:
1
2
(no 10 and 11)
But now what I want to do is list the name of the children under their parent, so it ends up something like this:
1
Tom
Peter
2
I have an array of the children ids, I'm just not sure how to reloop through the original array for the names.
Will assume your array is one level deep, a parent_id == null signifies a parent and there are no possible orphan elements that should be displayed:
foreach($array as $key => $value) {
if ($value['parent_id'] === null) {
echo $key;
// we got a parent, iterate through it's children
foreach($value['children'] as $childId) {
echo $array[$childId]['name'];
}
}
}
May want to add some empty checks, just to make sure all keys exist in the array.

Categories