It is possible sum values by keys? how do it (php) - php

Array for example
$array = array(
array('first'=>5), array('first'=>4), array('second'=>3)
);
How sum values by keys for result:
$result = array(
'first'=>9,
'second'=>3
);

you can iterate array $array and do whatever you want. And you can do it with any language if you have some pprogramming skills.
$result=array();
foreach ($array as $sub) {
foreach ($sub as $key => $value) {
if (isset($result[$key])) $result[$key] += $value;
else $result[$key]=$value;
}
}
Note: if you getting this info from database, it is better to sum it using database resources.

You can use array_walk_recursive:
$results = array();
array_walk_recursive($array, function($number, $key){
global $results;
if (! isset($results[$key])) $results[$key] = 0;
$results[$key] += $number;
});
This works in php >= 5.3

Related

PHP read value form multidimensional array

its easy for sure..
i have code like this:
$indeks = 0;
foreach ($list as $k => $v)
{
$data['fname'] = $customer->firstname;
$data['lname'] = $customer->lastname;
$data['code'] = $code['code'];
$tablica[$indeks] = $data;
$indeks++;
and i want to read only 'code' value for each array.
i try:
foreach($tablica as $k => $v){
foreach ($v as $key => $value ) {
echo $value
}
}
but i get all arrays values.
when i try
foreach($tablica as $k => $v){
foreach ($v['code'] as $key => $value ) {
echo $value
}
}
i have nothing...
thx for help
You can use array_column function to get all values of column, for example:
foreach (array_column($tablica, 'code') as $value) {
echo $value;
}
I think a For loop should help
for($i=0;$i<count($tablica);$i++){
echo $tablica[$i]['code'];
}
or get all Codes into an Array
$code = array();
for($i=0;$i<count($tablica);$i++){
$code[$i] = $tablica[$i]['code'];
}
You don't need nested loops.
foreach ($tablica as $value) {
echo $value['code'];
}
DEMO

Incrementing value of an array from another array

I have 2 arrays
$array1 = array(22,193,124);
$array2 = array(array('id'=>22, 'count'=> 1), array('id'=>124, 'count'=>2));
Now I need to search in $array2 for id from $array1 and if found to increment the count value and also add to the array the one's which are not found with a count as 1 so my resulting array would be
$arr = array(array('id'=>22, 'count'=> 2), array('id'=>124, 'count'=>3), array('id'=>193, 'count'=>1));
any help would be appreciated
The current code which I tried is
if($array2){
foreach($array1 as $array){
if(in_array($array, array_column($array2, 'id'))){
$wa_array['count'] += 1;
} else {
$wa_array['id'] = $array;
$wa_array['count'] = 1;
}
}
} else {
foreach($array1 as $array){
$wa_array['id'] = $array;
$wa_array['count'] = 1;
}
}
This may be something you are looking for -
$array1 = array(22,193,124);
$array2 = array(array('id'=>22, 'count'=> 1), array('id'=>124, 'count'=>2));
foreach($array1 as $key=>$digit)
{
$keyFound = array_search($digit, array_column($array2, 'id'));
if($keyFound === false)
{
array_push($array2, ['id'=>$digit, 'count'=>1]);
}
else
{
$array2[$keyFound]['count']++;
}
}
print_r($array2);
The question is not so clear, so I will go with my understanding : You need to check if values inside the first array are in the second array. If yes, increment the count value of that second array, if not, create that element with the value of 1.
This code is not tested, hope this can help find the good solution.
foreach($array1 as $value){
searchForId($value,$array2);
}
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['id'] === $id) {
$val['count'] += 1;
}else{
array_push(array('id'=>$id,'count'=>1))
}
}
return null;
}
you should loop through $array2, not $array1. Finding the value in array_column($array2, 'id') doesn't tell you the index of the array element to increment.
foreach ($array2 as &$item) {
if (in_array($item['id'], $array1)) {
$item['count']++;
}
}
Note that you have to use &$item to make this a reference to the original array element, so that modifying it will update $array2. Otherwise, $item would be a copy of the array element.
If $array1 is large, it would be better to convert it to an associative array so you can test membership more efficiently.
$array1_assoc = array_flip($array1);
Then the test in the loop becomes:
if (isset($array1_assoc[$item['id']]) {
Check this one. NOTE: But this has O(n^2) complexity.
$array1 = [22,193,124];
$array2 = [['id'=>22, 'count'=> 1], ['id'=>124, 'count'=>2]];
foreach ($array1 as $value) {
$isFound = false;
foreach ($array2 as &$item) {
if ($value == $item['id']) {
$item['count']++;
$isFound = true;
continue;
}
}
if ($isFound == false) {
$array2 [] = ['id'=>$value, 'count'=> 1];
}
}
var_dump($array2);

Laravel, how to change array key permanently?

Tried using array_values but it only temporary.
controller
foreach($rows as $key => $value)
{
array_values($value);
//dd shows the key changes to [0], [1], [2] and so on
}
You can do it like this,
$rows = array_map(function($v){return array_values($v);}, $rows);
Something like this should work:
$new = [];
foreach($rows as $key => $value)
{
array_values($value);
$sub = [];
foreach ($value as $subKey => $subValue) {
$subKey = $key;
$sub[$key] = $subValue;
}
$new[$key] = $sub;
//dd shows the key changes to [0], [1], [2] and so on
}
Then return $new instead of $rows.
Since you're using laravel you can also do:
$rows = collect($rows)->map(function ($value) {
return Arr::accessible($value)?collect($value)->values()->all():$value;
})->all();
If you are trying to change the associative array to an indexed array, do this:
$array = array_values($array);

How to search(matchings) more than one values in an php array?

In php we have array_search() to search a value in an array. According to my knowledge it can search only one value at a time. How to search more that one values in an array. Are there any functions to do so.
Thanks
I'm not sure if there is a function for it, but you could do that in a foreach loop quite easily.
<?php
$array('some', 'values', 'here');
$values = array('values', 'to', 'find');
foreach($values as $v) {
$key = array_search($v, $array):
if ($key) {
$new_array[] = $array[$key];
}
}
?
try this:
$array = array('some', 'values', 'here');
$values = array('values', 'to', 'find');
foreach($values as $v) {
$key = array_search($v, $array);
if ($key) {
$new_array[] = $array[$key];
}
}

return monodimensional-array from multidimensional

I have a multidimensional array:
$array=array( 0=>array('text'=>'text1','desc'=>'blablabla'),
1=>array('text'=>'text2','desc'=>'blablabla'),
2=>array('text'=>'blablabla','desc'=>'blablabla'));
Is there a function to return a monodimensional array based on the $text values?
Example:
monoarray($array);
//returns: array(0=>'text1',1=>'text2',2=>'blablabla');
Maybe a built-in function?
This will return array with first values in inner arrays:
$ar = array_map('array_shift', $array);
For last values this will do:
$ar = array_map('array_pop', $array);
If you want to take another element from inner array's, you must wrote your own function (PHP 5.3 attitude):
$ar = array_map(function($a) {
return $a[(key you want to return)];
}, $array);
Do it like this:
function GetItOut($multiarray, $FindKey)
{
$result = array();
foreach($multiarray as $MultiKey => $array)
$result[$MultiKey] = $array[$FindKey];
return $result;
}
$Result = GetItOut($multiarray, 'text');
print_r($Result);
Easiest way is to define your own function, with a foreach loop. You could probably use one of the numerous php array functions, but it's probably not worth your time.
The foreach loop would look something like:
function monoarray($myArray) {
$output = array();
foreach($myArray as $key=>$value) {
if( $key == 'text' ) {
$output[] = $value;
}
}
return $output;
}
If the order of your keys never changes (i.e.: text is always the first one), you can use:
$new_array = array_map('current', $array);
Otherwise, you can use:
$new_array = array_map(function($val) {
return $val['text'];
}, $array);
Or:
$new_array = array();
foreach ($array as $val) {
$new_array[] = $val['text'];
}
Try this:
function monoarray($array)
{
$result = array();
if (is_array($array) === true)
{
foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $value)
{
$result[] = $value;
}
}
return $result;
}
With PHP, you only have to use the function print_r();
So --> print_r($array);
Hope that will help you :D

Categories