php array sum for same value - php

I have this array:
Array ( [0] =>
Array (
[0] => Array (
[07] => Array (
[2] => 352.9
[3] => 375737
[4] => 1000000002
) )
[1] => Array (
[07] => Array (
[2] => 362.1
[3] => 375797
[4] => 1000000002
) )
)
Array ( [1] =>
[0] => Array (
[08] => Array (
[2] => 305.7
[3] => 375857
[4] => 1000000002
) )
)
)
i need a final array sum for the key 07 ( is the month ) like this:
Array ( [0] =>
Array (
[0] => Array (
[07] => Array (
[2] => 3254.9 ( the sum of each 07 )
[3] => 6521545 ( the sum )
[4] => 98474916521621 ( the sum )
) )
)
Array ( [1] =>
[0] => Array (
[08] => Array (
[2] => 305.7 ( not summed cause month 08 is only one )
[3] => 375857 ""
[4] => 1000000002 ""
) )
)
)
Any help?

Here, try this - I'm sure it's neither a perfect nor optimal solution ( 3 foreach-es ), but it works on a reasonably large data set...
$inputArray is the multidimensional array with the data you provided, btw...
EDIT: Fixed version:
$result = array();
foreach( $inputArray as $subArray ) {
foreach ( $subArray as $subKey => $member ) {
if ( empty( $result[$subKey]) ) {
$result[$subKey] = $member;
} else {
foreach ( $member as $id => $subMember ) {
if ( empty( $result[$subKey][$id]) ) {
$result[$subKey][$id] = $subMember;
} else {
$result[$subKey][$id] += $subMember;
}
}
}
}
}
EDIT2: Since you changed the format of arrays, the solution is different:
Note: $array1 and $array2 are your "global" - predefined arrays.
$arrayWrapper = array_merge( ( array ) $array1, ( array ) $array2 );
$result = array();
foreach ( $arrayWrapper as $inputArray ) {
foreach( $inputArray as $subArray ) {
foreach ( $subArray as $subKey => $member ) {
if ( empty( $result[$subKey]) ) {
$result[$subKey] = $member;
} else {
foreach ( $member as $id => $subMember ) {
if ( empty( $result[$subKey][$id]) ) {
$result[$subKey][$id] = $subMember;
} else {
$result[$subKey][$id] += $subMember;
}
}
}
}
}
}
Tested it with your data, should work.
Cheers.

Related

How to store array with array_push() outside loop?

I have an array, when i tried to print_r was just like this :
Array ( [user_id] => Erick ) Array ( [user_id] => Baldi) Array([user_id]=> Bintang ) Array ( [user_id] => Bagas ) Array ( [user_id] => Baim )
My Expected output just like :
Array (
Array (
[user_id] => Erick
)
Array (
[user_id] => Baldi
)
Array (
[user_id] => Bintang
)
Array (
[user_id] => Bagas
)
Array (
[user_id] => Baim
)
)
Anyone here have an idea ? I'm stuck with this.
This my php code :
public function get_userid() {
// $action = $this->input->post('action');
$customerField = $this->input->post('customer');
$projectField = $this->input->post('project');
$user_roleField = $this->input->post('role');
for ($i=0; $i<count($customerField); $i++) {
for ($j=0; $j<count($projectField); $j++) {
for ($k=0; $k<count($user_roleField); $k++) {
array_push($test, $this->get_array_push($customerField[$i], $projectField[$j], $user_roleField[$k]));
}
}
}
}
public function get_array_push($customer, $project, $user_role) {
$query = $this->db->query("SELECT user_id
FROM `ixt_user_project_list`
LEFT JOIN ixt_user_type ON ixt_user_project_list.user_type = ixt_user_type.user_type
WHERE ixt_user_project_list.user_cust_id ='".$customer."'
AND ixt_user_project_list.user_project_id ='".$project."'
AND ixt_user_type.user_owner ='".$user_role."'")->result_array();
//Filter null array
foreach ($query as $key => $value) {
print_r($value);
}
}
And this is my initial query value :
Array ( [0] => Array ( [user_id] => Erick ) ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( [0] => Array ( [user_id] => Baldi ) [1] => Array ( [user_id] => Bintang ) ) Array ( [0] => Array ( [user_id] => Bagas ) [1] => Array ( [user_id] => Baim ) )
As #scaisEdge wrote - its happening because you use the print_r inside the foreach loop.
If you want to filter null result you can use array-filter as:
$arr = array(array("user_id" => "aaa"), null, array(), array("user_id" => null), array("otherField" => "bbb"));
$filterdResult = array_filter($arr, function($elem) {
return ($elem && array_key_exists("user_id", $elem) && !is_null($elem["user_id"]));
});
Now you can just do print_r($filterdResult );
This will output:
Array
(
[0] => Array
(
[user_id] => aaa
)
)
Edited: After setting your new input as:
$query = array(array(array("user_id" => "aaa"), null, array(), array("user_id" => null)), array(array("user_id" => "ccc"), null, array(),array("user_id" =>"ddd")));
You can use the following:
$res = array();
//Filter null array
foreach ($query as $key => $value) {
array_push($res, array_filter($value, function($elem) {
return ($elem && array_key_exists("user_id", $elem) && !is_null($elem["user_id"])); }));
}
print_r($res);
Which output:
Array
(
[0] => Array
(
[0] => Array
(
[user_id] => aaa
)
)
[1] => Array
(
[0] => Array
(
[user_id] => ccc
)
[3] => Array
(
[user_id] => ddd
)
)
)
From here flatten is available if needed.
#David Winder I tried to combine as your suggesstion with the null array filter.
$res = array();
//Filter null array
foreach ($query as $key => $value) {
if (!is_null($value)) {
$res[] = $value;
//print_r($res);
}
}
But when i print_r($res) inside the foreach loop the result became duplicate array inside all of the array value.

Compare different arrays structures

I have two arrays with different structures. Array 1 and Array 2 that I will name from MyList and MyFiles. I would get to return only MyList values that do not have in MyFiles. But the two arrays have different structures and I'm having trouble trying to compare
MyList
Array
(
[info] => Array
(
[0] => Array
(
[player] => Messi
[week] => Array
(
[id] => 252
[videos] => Array
(
[0] => Array
(
[id] => 2929850
[link] => goals.mp4
)
[1] => Array
(
[id] => 2929848
[link] => best.mp4
)
[2] => Array
(
[id] => 2929847
[link] => dribbling.mp4
)
)
)
)
[1] => Array
(
[player] => CR7
[week] => Array
(
[id] => 251
[videos] => Array
(
[0] => Array
(
[id] => 2929796
[link] => goals.mp4
)
[1] => Array
(
[id] => 2929795
[link] => best.mp4
)
)
)
)
[2] => Array
(
[player] => Neymar
[week] => Array
(
[id] => 253
[videos] => Array
(
[0] => Array
(
[id] => 2929794
[link] => goals.mp4
)
[1] => Array
(
[id] => 2929793
[link] => best.mp4
)
)
)
)
)
)
MyFiles Array
Array
(
[252] => Array
(
[0] => Array
(
[id] => 2929850
[link] => goals.mp4
)
[1] => Array
(
[id] => 2929848
[link] => best.mp4
)
)
[251] => Array
(
[0] => Array
(
[id] => 2929796
[link] => goals.mp4
)
[1] => Array
(
[id] => 2929795
[link] => best.mp4
)
)
)
the comparison must be made by id of the week and id of the video
I tried this but it did not work out:
$new = array();
foreach ($list['info'] as $source) {
foreach ($source["week"]['videos'] as $keys => $videos) {
foreach ($file as $key => $upload) {
if ($source["week"]["id"] == $key ) {
for($i=0; $i<count($source["week"]["videos"]); $i++){
if($videos["id"] == $upload[$i]["id"]){
unset($videos);
}else{
$new[] = $videos;
}
}
} else {
$new[] = $videos;
}
}
}
}
The expected return would be something like this.
Array
(
[info] => Array
(
[0] => Array
(
[player] => Messi
[week] => Array
(
[id] => 252
[videos] => Array
(
[2] => Array
(
[id] => 2929847
[link] => dribbling.mp4
)
)
)
)
[2] => Array
(
[player] => Neymar
[week] => Array
(
[id] => 253
[videos] => Array
(
[0] => Array
(
[id] => 2929794
[link] => goals.mp4
)
[1] => Array
(
[id] => 2929793
[link] => best.mp4
)
)
)
)
)
)
I have hidden the array in a usable format for my sake in the future should this answer be incorrect and need changing.
$desired = array();
$desired['info'][0]['player'] = 'Messi';
$desired['info'][0]['week']['id'] = 252;
$desired['info'][0]['week']['videos'][2]['id'] = 2929847;
$desired['info'][0]['week']['videos'][2]['link'] = 'dribbling.mp4';
$desired['info'][2]['player'] = 'Neymar';
$desired['info'][2]['week']['id'] = 253;
$desired['info'][2]['week']['videos'][0]['id'] = 2929794;
$desired['info'][2]['week']['videos'][0]['link'] = 'goals.mp4';
$desired['info'][2]['week']['videos'][1]['id'] = 2929793;
$desired['info'][2]['week']['videos'][1]['link'] = 'best.mp4';
$list = array();
$list["info"][0]["player"] = "Messi";
$list["info"][0]["week"]["id"] = "252";
$list["info"][0]["week"]["videos"][0]["id"] = 2929850;
$list["info"][0]["week"]["videos"][0]["link"] = "goals.mp4";
$list["info"][0]["week"]["videos"][1]["id"] = 2929848;
$list["info"][0]["week"]["videos"][1]["link"] = "best.mp4";
$list["info"][0]["week"]["videos"][2]["id"] = 2929847;
$list["info"][0]["week"]["videos"][2]["link"] = "dribbling.mp4";
$list["info"][1]["player"] = "CR7";
$list["info"][1]["week"]["id"] = "251";
$list["info"][1]["week"]["videos"][0]["id"] = 2929796;
$list["info"][1]["week"]["videos"][0]["link"] = "goals.mp4";
$list["info"][1]["week"]["videos"][1]["id"] = 2929795;
$list["info"][1]["week"]["videos"][1]["link"] = "best.mp4";
$list["info"][2]["player"] = "Neymar";
$list["info"][2]["week"]["id"] = "253";
$list["info"][2]["week"]["videos"][0]["id"] = 2929794;
$list["info"][2]["week"]["videos"][0]["link"] = "goals.mp4";
$list["info"][2]["week"]["videos"][1]["id"] = 2929793;
$list["info"][2]["week"]["videos"][1]["link"] = "best.mp4";
$file = array();
$file[252][0]['id'] = 2929850;
$file[252][0]['link'] = 'goals.mp4';
$file[252][1]['id'] = 2929848;
$file[252][1]['link'] = 'best.mp4';
$file[251][0]['id'] = 2929796;
$file[251][0]['link'] = 'goals.mp4';
$file[251][1]['id'] = 2929795;
$file[251][1]['link'] = 'best.mp4';
Edit
function array_diff_assoc_recursive($array1, $array2) {
$difference=array();
foreach ($array1 as $key => $value) {
if (is_array($value)) {
if( !isset($array2[$key]) || !is_array($array2[$key])) {
$difference[$key] = $value;
} else {
$new_diff = array_diff_assoc_recursive($value, $array2[$key]);
if (!empty($new_diff))
$difference[$key] = $new_diff;
}
} else if (!array_key_exists($key,$array2) || $array2[$key] !== $value) {
$difference[$key] = $value;
}
}
return $difference;
}
$new = array('info' => array());
foreach ($list['info'] as $key => $item) {
$a = $item['week']['videos'];
//$b = $file[$item['week']['id']] ?? []; // This is PHP7+
$b = isset($file[$item['week']['id']]) ? $file[$item['week']['id']] : [];
$c = array_diff_assoc_recursive($a, $b);
if (!empty($c)) {
$new['info'][$key] = $item;
$new['info'][$key]['week']['videos'] = $c;
}
}
You will need a function that will check the difference between the videos arrays.
What I do is simply iterate over the list array and then check the difference between that item and the file array. The difference is then stored in $c.
If there is a difference then if statement is fired which will store that player in the $new array and then replace the videos array with the difference array.
This is similar to what you were doing when you were unsetting variables.

Why array value is giving 0?

I am reading a whole bunch of data from my users and adding them as associative arrays to be able to join the data. the following gives me the correct arrays values but then I get 0 as a result.
<?php
$userID = array();
$blogusers = get_users( 'orderby=nicename&role=author' );
foreach ( $blogusers as $user ) {
$gender = 'sesso';
$single = true;
$the_user_id = $user->ID;
array_push($userID, $the_user_id);
$myUsers = $user->user_description;
$user_sex = get_user_meta( $the_user_id, $gender, $single );
$users[$user->ID] = array( "description" => $myUsers , "gender" => $user_sex );
}
$roles = array();
foreach($users as $id => $values){
$temp_roles = explode(',', $values['description']);
foreach($temp_roles as $k => $v){
$roles[trim($v)][$values['gender']][] = true;
}
}
?>
<ul class="margin-top-20">
<?php
foreach($roles as $skill => $genderB) {
$males = count($genderB['male']);
$females = count($genderB['female']);
$total = $males + $females;
echo $females;
echo "<li>We have ".$total." ".$skill." teachers, ".$males." males, ".$females." females</li>";
}
?>
</ul>
I get 0 if I do echo $females; and the strings all get 0 as values
We have 0 francese teachers, 0 males, 0 females
if I do print_r($users[$user->ID] ); right at the end of the first foreach, i get the right result tho
Array ( [description] => francese, chimica, fisica, scienze [gender] => Array ( [0] => maschio ) ) Array ( [description] => inglese, fisica, chimica, spagnolo [gender] => Array ( [0] => maschio ) ) Array ( [description] => francese, fisica, italiano [gender] => Array ( [0] => femmina ) )
And if I do print_r($roles); at the end of the second foreach i get only the roles values but not the gender
Array ( [francese] => Array ( ) [chimica] => Array ( ) [fisica] => Array ( ) [scienze] => Array ( ) ) Array ( [francese] => Array ( ) [chimica] => Array ( ) [fisica] => Array ( ) [scienze] => Array ( ) [inglese] => Array ( ) [spagnolo] => Array ( ) ) Array ( [francese] => Array ( ) [chimica] => Array ( ) [fisica] => Array ( ) [scienze] => Array ( ) [inglese] => Array ( ) [spagnolo] => Array ( ) [italiano] => Array ( )
The again if I do print_r($temp_roles); at the end of the second foreach i get
Array ( [0] => francese [1] => chimica [2] => fisica [3] => scienze ) Array ( [0] => inglese [1] => fisica [2] => chimica [3] => spagnolo ) Array ( [0] => francese [1] => fisica [2] => italiano )
I don't understand why I am getting 0 values for all of them at the end
In your data the gender is defined by femmina and maschio. In your code you check for female and male.
The other problem I detected is that you do not have to have both male and female teachers. If you turn your error reporting on, with this code you will get
Undefined index: female (or male)
if there are no females. You can work arround it by $females = isset($genderB['female']) ? count(genderB['female']): 0;. Or by "full" if statement of course.

php - Iterate through array and order by dependencies

I was wondering if there is a known class/functions or any tutorials out there that can help in ordering an array by its dependency (stored as there value of the key pair).
i.e. (please note these are not actual dependancies)
Array
(
[blueimp-canvas-to-blob] => Array
(
)
[blueimp-load-image] => Array
(
[0] => jquery
)
[blueimp-tmpl] => Array
(
[0] => jquery
[1] => blueimp-load-image
)
[jquery] => Array
(
)
[blueimp-file-upload] => Array
(
[0] => jquery
[1] => blueimp-tmpl
[2] => blueimp-load-image
[3] => blueimp-canvas-to-blob
)
)
would be ordered as:
Array
(
[blueimp-canvas-to-blob] => Array
(
)
[jquery] => Array
(
)
[blueimp-load-image] => Array
(
[0] => jquery
)
[blueimp-tmpl] => Array
(
[0] => jquery
[1] => blueimp-load-image
)
[blueimp-file-upload] => Array
(
[0] => jquery
[1] => blueimp-tmpl
[2] => blueimp-load-image
[3] => blueimp-canvas-to-blob
)
)
any help would be greatly appreciated
Managed to figure this out (i think):
private function orderItems(){
while( ! empty( $this->order ) ) {
$item = array_splice( $this->order, 0, 1 );
$dependencies = end( $item );
$name = key( $item );
if( empty( $dependencies ) ) {
$this->ordered[$name] = $dependencies;
} else {
$satisafied = true;
foreach( $dependencies as $dependency ) {
if( isset( $this->order[$dependency] ) ) $satisafied = false;
}
if( $satisafied ) {
$this->ordered[$name] = $dependencies;
} else {
$this->order = $this->order + $item;
}
}
}
}
here if anyone else wants something simular

Array values update

I have an array like this..
Array
(
[0] => Array
(
[0] => 1``
[1] => 2``
[2] => 3``
)
[1] => Array
(
[0] => 4``
[1] => 5``
[2] => 6``
)
[2] => Array
(
[0] =>
[1] => 7``
[2] =>
)
)
I want the result like this below,
$remaining_value = Array
(
[0] => 1`` 4``,
[1] => 2`` 5`` 7``,
[2] => 3`` 6``,
)
How to do this in an single loop.. Plz help me..
If the lower-level arrays will always have the same number of elements then you can do something like this:
$subArrayCount = count( $inputArray );
$outputArray = array();
$firstSubArray = reset( $inputArray );
foreach( $firstSubArray as $key => $value )
{
$outputArray[$key] = $value;
for( $innerLoop = 1; $innerLoop < $subArrayCount; $innerLoop++ )
{
$outputArray[$key].= $inputArray[$innerLoop][$key];
}
}
var_dump( $outputArray );
This should work:
<?php
$remaining_value=array();
foreach($array as $loopv1){
foreach($loopv1 as $key2 => $loopv2){
if(empty($remaining_value[$key2]))$remaining_value[$key2]=$loopv2; else $remaining_value[$key2].=" ".$loopv2;
}
}
?>

Categories