Looping through multidimensional array in php - php

Please refer to array below. What I would like to do is to get the total of the values of index zero under 21 and 23 divided by the number of zeros. It is like getting their average.
Array
(
[21] => Array
(
[0] => 3.5
[65] => Array
(
[0] => 44.125
)
[150] => Array
(
[0] => 15.25
)
[151] => Array
(
[0] => 17.333333333333
)
)
[23] => Array
(
[0] => 0
[166] => Array
(
[0] => 26
)
[172] => Array
(
[0] =>
)
[182] => Array
(
[0] => 20.333333333333
)
[183] => Array
(
[0] => 24.125
)
)
)
Then format it to this
Array
(
[21] => Array
(
[0] => Average for 21
[65] => Array
(
[0] => 44.125
)
[150] => Array
(
[0] => 15.25
)
[151] => Array
(
[0] => 17.333333333333
)
)
[23] => Array
(
[0] => Average for 23
[166] => Array
(
[0] => 26
)
[172] => Array
(
[0] =>
)
[182] => Array
(
[0] => 20.333333333333
)
[183] => Array
(
[0] => 24.125
)
)
)
Thanks in advance to those who can help! :)
Note: This is just a sample structure of the array. It's possible that the children of 21 and 23 can have another children, meaning, another nodes. Example:
[65] => Array
(
[0] => 44.125
[x] => Array
(
[0]=> 121.11
)
)
I believe a recursive function is needed on this one.

try this, I think this is what you want
$count1 = 0;$sum=0;
$count2 = 0;$sum2=0;
foreach ($array as $key3 => $value3)
{
if($key3 == "21")
{
foreach ($value3 as $key => $value)
{
if (strpos($key, '0') === 0) {
$count1++;$sum=$sum+$value;
}
if(is_array($value))
{
foreach($value as $key2=>$value2)
{
if(strpos($key2,'0') === 0)
{
$count1++ ;$sum=$sum+$value2;
}
}
}
}
}
if($key3 == "23")
{
foreach ($value3 as $key => $value)
{
if (strpos($key, '0') === 0) {
$count2++;$sum2=$sum2+$value;
}
if(is_array($value))
{
foreach($value as $key2=>$value2)
{
if(strpos($key2,'0') === 0)
{
$count2++; $sum2=$sum2+$value2;
}
}
}
}
}
}
$array[21][0] = ($sum/$count1);
$array[23][0] = ($sum2/$count2);
Demo

Related

Delete element from triply nested array PHP

I am struggling to figure out how to remove elements from a triple nested array based on a value at the deepest level. I would like to remove any position sub-array where time == "NA". My array structure is as follows.
Array
(
[0] => Array
(
[Id] => 151601
[First_Name] => JOHN
[Last_Name] => DOE
[Location_Id] => 10
[Positions] => Array
(
[North] => Array
(
[Current_Level] => 4
[Last_Date] => 11/7/2001
[Time] => 4:15 AM
)
[East] => Array
(
[Current_Level] => 4
[Last_Date] => 7/10/2003
[Time] => 7:30 PM
)
[South] => Array
(
[Current_Level] => 2
[Last_Date] => 8/10/2007
[Time] => NA
)
[West] => Array
(
[Current_Level] => NA
[Last_Date] => NA
[Time] => NA
)
)
)
So my end result would be
Array
(
[0] => Array
(
[Id] => 151601
[First_Name] => JOHN
[Last_Name] => DOE
[Location_Id] => 10
[Positions] => Array
(
[North] => Array
(
[Current_Level] => 4
[Last_Date] => 11/7/2001
[Time] => 4:15 AM
)
[East] => Array
(
[Current_Level] => 4
[Last_Date] => 7/10/2003
[Time] => 7:30 PM
)
)
)
This is what I am currently trying but it is throwing an illegal offset type error. I think I'm just not unsetting the right thing. I can get it to echo all the correct subarrays but when I try to unset I get an offset error.
foreach($records as $record) {
foreach ($record as $value) {
if (is_array($value)) {
foreach ($value as $position) {
if($position["Time"] == "NA") {
unset($records[$record][$value]);
}
}
}
}
}
With passing array element by reference and filtering function you can reduce your code to:
foreach($records as &$record) {
$record['Positions'] = array_filter(
$record['Positions'],
function ($v) {
return $v['Time'] !== 'NA';
}
);
}
Fiddle here.
Php uses a copy of the array in the foreach. You might also use a key in the foreach and use that to unset the value in the original $records array.
foreach ($records as $keyRecord => $record) {
foreach ($record as $key => $value) {
if (is_array($value)) {
foreach ($value as $keyPosition => $position) {
if ($position["Time"] == "NA") {
unset($records[$keyRecord][$key][$keyPosition]);
}
}
}
}
}
print_r($records);
Output
Array
(
[0] => Array
(
[Id] => 151601
[First_name] => John
[Positions] => Array
(
[North] => Array
(
[Current_Level] => 4
[Last_Date] => 11/7/2001
[Time] => 4:15 AM
)
[East] => Array
(
[Current_Level] => 4
[Last_Date] => 7/10/2003
[Time] => 7:30 PM
)
)
)
)
Php demo

How to make array key from array data value in associative array

I have a multidimensional associative array which has a set of array. I want to change my array index value from some array value.
I already tried some array functions but my array also contains some null array so laravel function keyBy not give me wanted result.
$arr1=array(0 =>array(),1=>array(0=>array('quan'=>10,'handle' => 'baroque'),1 =>array('quan'=>20,'handle' => 'baroque')),
2 =>array (0 =>array('quan' => 5,'handle' => 'adidas')));
My expected result array must be like this
$arr2=array(0 =>array(),'baroque'=>array(0=>array('quan'=>10,'handle' => 'baroque'),1 =>array('quan'=>20,'handle' => 'baroque')),
'adidas' =>array (0 =>array('quan' => 5,'handle' => 'adidas')));
You can use the classic foreach. Check if the handle on element 0 exists using isset, if it does, use that as the key.
$arr1 = //...
$result = array();
foreach($arr1 as $key => $val) {
if (is_array($val) && isset($val[0]["handle"])) $result[ $val[0]["handle"] ] = $val;
else $result[$key] = $val;
}
$result will be:
Array
(
[0] => Array
(
)
[baroque] => Array
(
[0] => Array
(
[quan] => 10
[handle] => baroque
)
[1] => Array
(
[quan] => 20
[handle] => baroque
)
)
[adidas] => Array
(
[0] => Array
(
[quan] => 5
[handle] => adidas
)
)
)
You can use without condition by grouping at the handle as key directly.
$result = [];
foreach ($arr as $key => $value) {
if (!empty($value)) {
foreach ($value as $key1 => $value1) {
$result[$value1['handle']][] = $value1;
}
} else {
$result[] = $value;
}
}
Demo
Output:-
Array
(
[0] => Array
(
)
[baroque] => Array
(
[0] => Array
(
[quan] => 10
[handle] => baroque
)
[1] => Array
(
[quan] => 20
[handle] => baroque
)
)
[adidas] => Array
(
[0] => Array
(
[quan] => 5
[handle] => adidas
)
)
)
Try this..
$res = [];
foreach($x as $key => $value)
{
if(empty($value))
{
$res[] = $value;
}
else
{
foreach($value as $v => $k)
{
if(array_key_exists($k['handle'],$res))
{
$res[$k['handle']][] = ['quan' => $k['quan'],'handle' => $k['handle']];
}
else
{
$res[$k['handle']][0] = ['quan' => $k['quan'],'handle' => $k['handle']];
}
}
}
}
The result is going to be like this.
Array
(
[0] => Array
(
)
[baroque] => Array
(
[0] => Array
(
[quan] => 10
[handle] => baroque
)
[1] => Array
(
[quan] => 20
[handle] => baroque
)
)
[adidas] => Array
(
[0] => Array
(
[quan] => 5
[handle] => adidas
)
)
)

Create 2 dimensional array from 1 dimensional

How from this array:
Array
(
[0] => Array
(
[BLACK] => Array
(
[0] => 3171
[1] => 3173
[2] => 3175
)
[WHITE] => Array
(
[0] => 3170
[1] => 3172
[2] => 3174
)
)
[1] => Array
(
[SMALL] => Array
(
[0] => 3170
[1] => 3171
)
[MEDIUM] => Array
(
[0] => 3172
[1] => 3173
)
[LARGE] => Array
(
[0] => 3174
[1] => 3175
)
)
)
I could create something like this:
$array['BLACK']['SMALL'] = 3171;
$array['BLACK']['MEDIUM'] = 3173;
$array['BLACK']['LARGE'] = 3175;
$array['WHITE']['SMALL'] = 3170;
$array['WHITE']['MEDIUM'] = 3172;
$array['WHITE']['LARGE'] = 3174;
so create 2 dimensional array from 1 dimensional, where option is same.
<?php
$colors = array('BLACK' => array('3171','3173','3175'),'WHITE' => array('3170','3172','3174'));
$sizes = array('SMALL' => array('3170','3171'),'MEDIUM' => array('3172','3173'), 'LARGE' => array('3174','3175'));
$merged = array();
foreach ($colors as $c_key => $color) {
foreach ($color as $c_val) {
foreach ($sizes as $s_key => $size) {
foreach ($size as $s_val) {
if ($c_val == $s_val) {
$merged[$c_key][$s_key] = $c_val;
}
}
}
}
}
// var_dump($merged);
?>

Remove duplicates from an object array

I have an object array that looks like this:
Array
(
[0] =>Object
(
[ClassScheduleID] => 2263
[Name] => Workout 1
[Location] => Object
(
[BusinessID] => 1
)
)
[1] =>Object
(
[ClassScheduleID] => 2263
[Name] => Workout 1
[Location] => Object
(
[BusinessID] => 13
)
)
[2] =>Object
(
[ClassScheduleID] => 2264
[Name] => Workout 2
[Location] => Object
(
[BusinessID] => 22
)
)
I am looking to identify that the ClassScheduleID of 2263 is a duplicate, and remove the duplicate entry's entire object from the array. So that I get:
Array
(
[0] =>Object
(
[ClassScheduleID] => 2263
[Name] => Workout 1
[Location] => Object
(
[BusinessID] => 1
)
)
[1] =>Object
(
[ClassScheduleID] => 2264
[Name] => Workout 2
[Location] => Object
(
[BusinessID] => 22
)
)
I tried the solution proposed here
How to remove duplicate values from a multi-dimensional array in PHP
but the count() remained the same
$count = 0;
foreach($arrayObj as $key => $value) {
if ($value['ClassScheduleID'] == 2263) {
$count++;
}
if ($count > 1){
unset($arrayObj[$key]);
$count--;
}
}
It works: http://ideone.com/fork/zrdDtu
Edit: Modified to delete any duplicates:
foreach($arrayObj as $key => $value) {
$count = 0;
foreach($arrayObj as $nkey => $nvalue) {
if ($value['ClassScheduleID'] == $nvalue['ClassScheduleID']) {
$count++;
}
if ($count > 1){
unset($arrayObj[$key]);
$count--;
}
}
}
var_dump($arrayObj);
See it here: http://ideone.com/fork/85RCst
function get_unique_array($array)
{
$result = array_map("unserialize", array_unique(array_map("serialize", $array)));
foreach ($result as $key => $value)
{
if ( is_array($value) )
{
$result[$key] = get_unique_array($value);
}
}
return $result;
}
Demo: http://3v4l.org/WOTHi#v430

php add some value on specific location in multidimensional array

I have array like this
Array ([0] => Array ( [user_id] => 21 [email] => momod#modara.com [brand] => Array ( [0] => GOFUEL_W [1] => GOFUEL_USD_W ) ) [1] => Array ( [user_id] => 22 [email] => hemisphere#modara.com [brand] => Array ( [0] => GOFUEL_W ) ) [2] => Array ( [user_id] => 23 [email] => madoka#modara.com [brand] => Array ( [0] => GOFUEL_W [1] => GOFUEL_USD_W [2] => GOFUEL_BGD_W ) ) )
i want to locate user_id 22 and put this value "GO_FUEL_SGD_W" on brand, what should i do, so the view of array will look like this
Array ([0] => Array ( [user_id] => 21 [email] => momod#modara.com [brand] => Array ( [0] => GOFUEL_W [1] => GOFUEL_USD_W ) ) [1] => Array ( [user_id] => 22 [email] => hemisphere#modara.com [brand] => Array ( [0] => GOFUEL_W => [1] =>GO_FUEL_SGD_W ) ) [2] => Array ( [user_id] => 23 [email] => madoka#modara.com [brand] => Array ( [0] => GOFUEL_W [1] => GOFUEL_USD_W [2] => GOFUEL_BGD_W ) ) )
Just use loop:
foreach($array as &$item)
{
if(array_key_exists('user_id', $item) &&
$item['user_id']==22 &&
array_key_exists('brand', $item) &&
!in_array('GO_FUEL_SGD_W', $item['brand']))
{
$item['brand'][] = 'GO_FUEL_SGD_W';
}
}
A simple foreach loop will do the job:
foreach($myarray AS &$subarray) {
if($subarray['user_id'] == 22) {
$subarray['brand'][] = "GO_FUEL_SGD_W";
break;
}
}
Working example: http://3v4l.org/8aQMj
You will need to iterate over the array and look for the element you're searching for.
foreach ($array as &$element) {
if ($element['user_id'] != 22)
continue;
$element['brand'][] = "GO_FUEL_SGD_W";
break;
}
With continue; all elements will be skipped, who have $element['user_id'] != 22 (and so none of the code after the continue; will be applied to them!).
Also it will end the loop once the requested element is reached and modified, thanks to break;.
$array= //your array;
foreach($array as $x){
if($x['user_id']=='22'){
$x['brand'][]='GO_FUEL_SGD_W';
break;
}
}

Categories