add all values with matching key in multidimensional json array - php

I am working on a php script where I have a json api array that looks something like this --
[body] => stdClass Object
(
[api] => stdClass Object
(
[status] => 200
[message] => GET stat....
[results] => 379
[filters] => Array
(
[0] => gameId
[1] => playerId
)
[statistics] => Array
(
[0] => stdClass Object
(
[gameId] => 17
[totReb] => 7
[assists] => 5
[pFouls] => 4
[steals] => 3
[turnovers] => 2
[blocks] => 0
[plusMinus] => 9
[playerId] => 265
)
[1] => stdClass Object
(
[gameId] => 24
[teamId] => 7
[totReb] =>
[assists] =>
[pFouls] =>
[steals] =>
[turnovers] =>
[blocks] =>
[plusMinus] =>
[playerId] => 265
)
And I am trying to get the values for each object to then output the total, so for each [?] => stdClass Object it will get the specified key and total the value.
How can I add all the values from one key?

First get the array of statistics (the one you want to loop and sum on). Then use array_column to extract only specific key and then array_sum for summing it.
This is pseudo but should give you the idea:
$arr = $obj->body->api->statistics;
$keyToSum = "steals";
$totalSteals = array_sum(array_column($arr, $keyToSum));
Reference: array-column, array-sum

There is one custom function I have which fetches column data recursively like array_column.
function array_column_recursive(array $haystack, $needle) {
$found = [];
array_walk_recursive($haystack, function($value, $key) use (&$found, $needle) {
if ($key == $needle)
$found[] = $value;
});
return $found;
}
echo array_sum(array_column_recursive($arr, 'steals'));
Source link.

Related

Creating a new associative array using values of the nested multi dimensional array in php

I have following multi dimensional array, I'm getting this from an API via curl request.
Array
(
[0] => Array
(
[id] => 1
[name] => David Warner
[type] => batter
[country] => Aus
[age] => 33
[runs] => 11100
[wickets] => 12
[catches] => 16
[format] => Array
(
[0] => Array
(
[Domestic] => Array
(
[0] => Array
(
[ODI] => 73
[Tests] => 34
[T20] => 90
)
)
)
)
)
[1] => Array
(
[id] => 2
[name] => Mark Wood
[type] => bowler
[country] => Eng
[age] => 34
[runs] => 200
[wickets] => 120
[catches] => 2
[format] => Array
(
[0] => Array
(
[Domestic] => Array
(
[0] => Array
(
[ODI] => 40
[Tests] => 49
[T20] => 12
)
)
)
)
)
)
I'm trying to create a new array which includes only the "[T20]" values.
My desired out put should look similar to the following array
array:2 [▼
0 => "90"
1 => "12"
]
So far, I've tried following methods...
$newArr_t20 = array_column($result_3['cricketers']['player']['format']['Domestic'], "T20");
Since I'm using laravel then I tried following as well,
use \Illuminate\Support\Arr;
$newArr_t20 = Arr::pluck($result_3, 'cricketers.player.format.Domestic.T20');
But nothing is working for me...
You can try this:
$array = 'Your array...';
$t20_values = [];
foreach ($array as $value) {
foreach ($value['format'] as $format) {
foreach ($format['Domestic'] as $domestic) {
if (isset($domestic['T20'])) {
$t20_values[] = $domestic['T20'];
}
}
}
}
dd($t20_values);
Using Laravel the collection helper Collection::flatten() should be the right way;
$data = collect($apiData)->flatten(4)->pluck('T20')->all();
Explanation:
Transform your array into a collection to be able to use the Laravel collection's provided helpers:
collect($apiData)
Transform your multidimensional array into a single dimensional one, which is nothing more than the array at the n-th depth (4 here in this case):
collect($apiData)->flatten(4)
Map this array into an array having only the values of the T20 key
collect($apiData)->flatten(4)->pluck('T20')
Get the array representation of the collection
collect($apiData)->flatten(4)->pluck('T20')->all()

Looping through 2 arrays and retrieve the values from the first array if the id matches with the second array. (PHP)

I've been trying to figure out how I would be able to loop through two arrays and match values from each array which should only return the value that matches of the first array.
Array 1:
[0] => Array
(
[contact] => 68
[field] => 11
[value] => DBSA
[cdate] => 2019-11-14T11:21:08-06:00
[udate] => 2021-03-30T07:54:00-05:00
)
[1] => Array
(
[contact] => 68
[field] => 131
[value] => ABC
[cdate] => 2019-11-22T08:34:03-06:00
[udate] => 2021-03-30T07:54:00-05:00
)
Array 2:
[0] => Array
(
[source] => analysis_utm_source
[id] => 131
)
[1] => Array
(
[source] => analysis_utm_medium
[destination] => UTM medium
[id] => 132
)
So in this example I would like to retrieve the values from the first array but only where id/field = 131
I've tried to work with 'array_intersect' but this doesn't seem to give the right output.
I'd appreciate it if someone would be able to push me in the right direction.
EDIT: I've been able to solve it by using array_filter, final code like so;
foreach ($fieldValuesDB as $arr) {
$options[] = $arr['id'];
}
$result = array_filter($fieldValuesAC, function($v) use ($options) {
return in_array($v['field'], $options);
});
foreach($array2 as $k => $v)
{
$key = array_search($v['id'], array_column($array1, 'field'));
if($key){
echo print_r($array1[$key]);
}
}
you will get the index of the element in your first array stored in $key variable

PHP - Merge 2 arrays of object using a key/id

I want to merge the 2 arrays of objects based on the 'id' field of Array1 and the 'itemVendorCode' of Array2. I also wanted to remove from the resulting arrays of object anything that didn't match.
Array1:
Array
(
[0] => stdClass Object
(
[id] => 10-423-1176
[qty] => 2
[price] => 12.6
)
[1] => stdClass Object
(
[id] => 89-575-2354
[qty] => 24
[price] => 230.35
)
[2] => stdClass Object
(
[id] => 89-605-1250
[qty] => 2
[price] => 230.35
)
)
Array2:
Array
(
[0] => Item Object
(
[internalId] => 14062
[itemVendorCode] => 89-605-1250
)
[1] => Item Object
(
[internalId] => 33806
[itemVendorCode] => 89-575-2354
)
[2] => Item Object
(
[internalId] => 64126
[itemVendorCode] => 26-295-1006
)
)
I was able to solve this by this code:
$indexed = array();
foreach($itemsArray as $value) {
$indexed[$value->itemVendorCode] = $value;
}
$results = array();
foreach($vendorItems as $obj) {
$value = $indexed[$obj->id];
if (isset($value)) {
foreach($value as $name => $val) {
$obj->$name = $val;
array_push($results, $obj);
}
}
}
print_r($results);
credits to the original poster. I just modified it a bit,
I was able to get the result like this:
Array
(
[0] => stdClass Object
(
[id] => 10-423-1176
[qty] => 2
[price] => 12.6
[internalId] => 2035
[itemVendorCode] => 10-423-1176
)
[1] => stdClass Object
(
[id] => 10-423-1176
[qty] => 2
[price] => 12.6
[internalId] => 2035
[itemVendorCode] => 10-423-1176
)
[2] => stdClass Object
(
[id] => 14-102-1010
[qty] => 16
[price] => 3.2
[internalId] => 57033
[itemVendorCode] => 14-102-1010
)
)
I think you will have to use array_map function which provides you a callback function to execute on array(s).
In the callback function:
- declare your array1
- foreach the second array
- set an if statement to check that the current iteration with the id value matches the itemVendorCode of the array2 and return it
something like this:
// You have to specify to PHP to use a local copy of your $array2 to works with it into your callback
$cb = function ($obj1) use ($array2)
{
// you foreach this array
foreach ($array2 as $obj2) {
// if the value of id matches itemVendorCode
if ($obj1->id === $obj2->itemVendorCode) {
// you return the id
return $obj->id;
}
}
};
// this function will fill a new array with all returned data
$mergedArray = array_map($cb, $array1);
This code is a sample but doesn't provide you, your needled solution, try to update it to do what you exactly want ;)

add new index using array map function in php without using looping function

this is my array
Array
(
[0] => Array
(
[id] => 277558
[text_value] => Jif
[response_count] => 13
[response_percentage] => 92
)
[1] => Array
(
[id] => 277559
[text_value] => Peter Pan
[response_count] => 20
[response_percentage] => 6
)
)
after completing the operation the out put should be
Array
(
[0] => Array
(
[id] => 277558
[text_value] => Jif
[response_count] => 13
[response_percentage] => 92
[encode_param]=>ds!##^(*!ggsfh8236542jsdgf82*&61327
)
[1] => Array
(
[id] => 277559
[text_value] => Peter Pan
[response_count] => 20
[response_percentage] => 6
[encode_param]=>ds!##^(*!ggsfh8236542jsdgf82*&61327
)
)
you can see a new array value encode_paramis added
in that function do some encode algorithms
i have achieve this in the foreach looping statement
but i need to do it in array maping
Can anybody help thank u in advance
$encode_func = function($elem) { // declare function to encode
return $elem['text_value'];
}
$result = array_map(function($elem) use($encode_func) {
$elem['encode_param'] = $encode_func($elem);
return $elem;
}, $array);
Hope it helps.

How to Get Specific key array in php without any loop

I have one multi dimentional array, the problem is I want the array values of specific key. I already tried current() and end() of array which is not useful to me. So please suggest me appropriate solution to find array values of specific key without using any loop. My Demo array is
Array
(
[0] => Array
(
[EntityType] => Array
(
[Id] => 1
[Code] => SUP/13-14/10001
[Name] => Supplier
[DisplayName] => Supplier
[ModuleIdentifier] => 1
[IsAdd] =>
[IsEdit] => 1
[IsDelete] => 1
)
)
[1] => Array
(
[EntityType] => Array
(
[Id] => 2
[Code] => Emp/13-14-10002
[Name] => Employee
[DisplayName] => Employee
[ModuleIdentifier] => 1
[IsAdd] =>
[IsEdit] =>
[IsDelete] =>
)
)
[2] => Array
(
[EntityType] => Array
(
[Id] => 3
[Code] => CUS/13-14/10003
[Name] => Customer
[DisplayName] => Customer
[ModuleIdentifier] => 1
[IsAdd] => 1
[IsEdit] =>
[IsDelete] =>
)
)
)
I want array having name Customer. So how to get these array...
Thanks !
You may use array_filter in conjunction with array_map:
function findElem($array, $val) {
$result = array_map(
function ($v) { return $v['EntityType']; },
array_filter($array, function ($v) use($val) { return $v['EntityType']['Name'] == $val; })
);
return count($result)? $result[0] : false;
}
print_r(findElem($array, 'Customer'));
If you want to access n'th element of your array just try with:
$array[n]
Where n is an integer value, so:
$array[2]
This line will get you all values of the key "Name" assuming your source array is named $arr if that's what you wanted:
$names = array_map( function($item) { return $item["EntityType"]["Name"]; } , $arr );
You can access your array data like this: $array[0]["EntityType"]["ID"].

Categories