I want a user defined function for sorting a multi dimension array:
<?php
$arr1 = array(
49,
8,
array(
'Muazam',
'Ali',
'Rana',
'Amina',
'Surya',
'Danish',
'Raina',
4,
3,
2,
1,
) ,
7,
6,
5,
4,
3,
2,
1,
0,
);
function abc($arr)
{
$len = count($arr) - 2;
foreach($arr as $key => $value)
{
for ($a = 0; $a <= $len; $a++)
{
if ($arr[$a] > $arr[$a + 1])
{
$temp4 = $arr[$a];
$arr[$a] = $arr[$a + 1];
$arr[$a + 1] = $temp4;
}
}
if (is_array($value))
{
abc($value, $a = $a + 1);
}
}
} //2nd foreach close
echo "<pre>";
print_r($arr);
echo "</pre>";
}
This is a basic usage of a recursive function:
$arr1 = array(49, 8, array(
'Muazam', 'Ali', 'Rana', 'Amina', 'Surya', 'Danish', 'Raina', 4, 3, 2, 1,
), 7, 6, 5, 4, 3, 2, 1, 0);
function recursiveSort(&$array)
{
foreach ($array as &$value) {
if (is_array($value)) {
recursiveSort($value);
}
}
return sort($array);
}
recursiveSort($arr1);
echo '<pre>';
print_r($arr1);
echo '</pre>';
The result would be:
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
[6] => 6
[7] => 7
[8] => 8
[9] => 49
[10] => Array
(
[0] => Ali
[1] => Amina
[2] => Danish
[3] => Muazam
[4] => Raina
[5] => Rana
[6] => Surya
[7] => 1
[8] => 2
[9] => 3
[10] => 4
)
)
Here Is Answer.. Sorting a multi dimensional array without using built in function.
$arr1 = array(1,3,5,'2',array(99,55,array(111,444,array('a','r','p','e','t'),777),66,99),8,9,0,3,1);
function abc(&$arr)
{
$len=count($arr)-2;
foreach($arr as $key => &$value)
{
for ($a=0;$a<=$len;$a++){
if($arr[$a]>$arr[$a+1])
{
$temp4=$arr[$a];
$arr[$a]=$arr[$a+1];
$arr[$a+1]=$temp4;
}
}
if(is_array($value))
{
abc($value,$a=$a+1);
}
}//foreach close
//}//2nd foreach close
echo "<pre>";
return $arr;
echo "</pre>";
}//function close
print_r (abc($arr1));
Related
I have a code that I am trying to make work but I just can't!
I have 2 arrays: 1-> Diares 2-> The value corresponds to each diary entry.
$diarioNum = array( [0] => 1 [1] => 2 [2] => 1 [3] => 3 [4] => 5 [5] => 1 [6] => 1 );
$vintoBookSX = array( [0] => -0.5 [1] => -0.4 [2] => -0.6 [3] => -0.4 [4] => -0.4 [5] => -1 [6] => -1 );
In my case I have multiply diaries and in the database from which I extrapolate the data are not in order, so I had to do this code:
<?php
$con = array_count_values($diarioNum);
foreach ($con as $key => $value) {
$pos = array_keys($diarioNum, $key);
echo "Diario " .$key. "<br>";
foreach ($pos as $ke => $val) {
$vBKsx = $vintoBookSX[$val];
echo $vBKsx . "<br>";
}
}
?>
Output:
Diario 1
-0.5
-0.6
-1
-1
Diario 2
-0.4
Diario 3
-0.4
Diario 5
-0.4
my Database table:
my Database table
Now I have to sum values for each diary.
And then output it must be:
Diario 1
-3.1
Diario 2
-0.4
Diario 3
-0.4
Diario 5
-0.4
Can you help me please?
You seem to use a complicated way to do that, this is how I will do it (on PHP side):
$diarioNum = [ 1, 2, 1, 3, 5, 1, 1 ];
$vintoBookSX = [ -0.5, -0.4, -0.6, -0.4, -0.4, -1, -1 ];
$result = [];
foreach ($diarioNum as $k => $day) {
$result[$day][] = $vintoBookSX[$k];
}
print_r($result);
$sums = array_map('array_sum', $result);
print_r($sums);
demo
There's probably a better way to do it on DBMS side. Something like:
SELECT diarioNumero, SUM(VintoBook_SX)
FROM yourtable
GROUP BY diarioNumero
ORDER BY diarioNumero
Here is one more solution
$diarioNum = array(1, 2, 1, 3, 5, 1, 1 );
$vintoBookSX = array(-0.5, -0.4, -0.6, -0.4, -0.4, -1, -1 );
$result = array_fill_keys( array_unique($diarioNum), 0);
foreach ( $diarioNum as $key => $val ) {
$result[ $val ] += $vintoBookSX[ $key ];
}
foreach ( $result as $key => $val ) {
echo "Diario $key <br>";
echo $val . "<br>";
}
I have an array in PHP.
For example :
Array
(
[3] => 6
[2] => 4
[1] => 2
[4] => 8
[6] => 12
)
I need to shift the position of each value to the next index.
ie, The desired output is
Array
(
[3] => 12
[2] => 6
[1] => 4
[4] => 2
[6] => 8
)
I need to keep the keys unchanged and round shift the values.
Which is the simplest method to attain it?
What I already tried is
$lastValue = $array[array_keys($array)[4]];
$firstKey = array_keys($array)[0];
for ($i=4; $i>0; $i--) {
$array[array_keys($array)[$i]] = $array[array_keys($array)[$i-1]];
}
$array[$firstKey] = $lastValue;
print_r($array);
php is so coool ^_^
part of the idea ~stolen~ taken from #Peters solution, sorry, mate :)
<?php
$array =
[
3 => 6,
2 => 4,
1 => 2,
4 => 8,
6 => 12,
];
$newArray = array_combine(array_keys($array), array_merge([array_pop($array)], $array));
var_dump($newArray);
demo
You can do a round shift on the value. Demo
$array =
[
3 => 6,
2 => 4,
1 => 2,
4 => 8,
6 => 12,
];
$values = [null];
$keys = [];
foreach($array as $k => $v){
$keys[] = $k;
$values[] = $v;
}
$values[0] = $v;
array_pop($values);
$result = array_combine($keys,$values);
print_r($result);
I have get foreach loop in month and total month value count data in array print but only last value print in array
foreach($rawData as $Data)
{
$monthsss = $Data['month_no'];
if($monthsss=='1')
{
$arrayF['jan'] = $Data['month_count'];
}
else
{
$arrayF['jan'] = '0';
}
if($monthsss=='2')
{
$arrayF['feb'] = $Data['month_count'];
}
else
{
$arrayF['feb'] = '0';
}
}
When someone comments and asks Please show input and expected output. this is not done to give you more work, but there are many ways to achieve what you want but many answers can be wrong or require much more code (as with the accepted answer).
Presuming this is your data:
$rawData = [
['month_no' => 1, 'month_count' => 1],
['month_no' => 2, 'month_count' => 1],
['month_no' => 3, 'month_count' => 1],
['month_no' => 4, 'month_count' => 1],
['month_no' => 1, 'month_count' => 2],
['month_no' => 6, 'month_count' => 2],
['month_no' => 7, 'month_count' => 6],
['month_no' => 12, 'month_count' => 4],
];
Do you want just the summed up values?
<?php
$array = [];
foreach ($rawData as $data) {
$m = strtolower(DateTime::createFromFormat('!m', $data['month_no'])->format('M'));
$array[$m] = !isset($array[$m]) ? $data['month_count'] : $array[$m]+$data['month_count'];
}
print_r($array);
https://3v4l.org/vXgCL
Array
(
[jan] => 3
[feb] => 1
[mar] => 1
[apr] => 1
[jun] => 2
[jul] => 6
[dec] => 4
)
Or do you want an array of all the months with the summed up values:
<?php
$array = [];
foreach (range(1, 12) as $month) {
$m = strtolower(DateTime::createFromFormat('!m', $month)->format('M'));
$monthSet = array_filter($rawData, function ($v) use ($month) {
return $v['month_no'] === $month;
});
$array[$m] = 0;
foreach ($monthSet as $data) {
$array[$m] += $data['month_count'];
}
}
print_r($array);
https://3v4l.org/vqnnv
Array
(
[jan] => 3
[feb] => 1
[mar] => 1
[apr] => 1
[may] => 0
[jun] => 2
[jul] => 6
[aug] => 0
[sep] => 0
[oct] => 0
[nov] => 0
[dec] => 4
)
Or perhaps don't even care about the month's strings as your comment suggests.
<?php
$array = [];
foreach ($rawData as $data) {
$m = $data['month_no'];
$array[$m] = !isset($array[$m]) ? $data['month_count'] : $array[$m]+$data['month_count'];
}
print_r($array);
https://3v4l.org/7gKRo
Array
(
[1] => 3
[2] => 1
[3] => 1
[4] => 1
[6] => 2
[7] => 6
[12] => 4
)
Its why we ask..
Please modify your code as follows
foreach($rawData as $Data)
{
$monthsss = $Data['month_no'];
if($monthsss=='1')
{
$arrayF['jan'] = is_null($Data['month_count'])? 0 : $Data['month_count'];
}
if($monthsss=='2')
{
$arrayF['feb'] = is_null($Data['month_count'])? 0 : $Data['month_count'];
}
}
Below is an example of a function that adds a constant number to the keys of an array -
function addConstantToArrayKeys($seed_array, $constant)
{
foreach($seed_array as $key => $value){
$a[$key + $constant] = $value;
}
return $a;
}
$basearray = [1 => 17, 2 => 24, 3 => 12];
$test = addConstantToArrayKeys($basearray, 19);
The result of this example is:
Array
(
[1] => 17
[2] => 24
[3] => 12
)
Array
(
[20] => 17
[21] => 24
[22] => 12
)
It works as desired but can this method be rewritten somehow using a functional programming approach that can achieve the same result?
I have tried this:
function addConstantToArrayKeys($seed_array, $constant)
{
return array_map(function($key, $element) use($constant)
{return $a[$key + $constant] = $element;},
array_keys($seed_array), array_values($seed_array));
}
But it does not handle the keys as desired. Here is the output -
Array
(
[1] => 17
[2] => 24
[3] => 12
)
Array
(
[0] => 17
[1] => 24
[2] => 12
)
Edit -
Thanks to Progrock's answer, this worked -
function addConstantToArrayKeys($seed_array, $constant)
{
return array_combine(array_map(
function($key) use($constant) {
return $key + $constant;
}, array_keys($seed_array)), $seed_array);
}
May be its too late but this should work for you as you wanted the functional approach.
function addConstantToArrayKeys($basearray, $constant){
$arrayReindexed = [];
array_walk($basearray,function($v,$k) use (&$arrayReindexed, $constant) {
$key = $k;
$k = $key + $constant;
$arrayReindexed[$k] = $v;
});
return $arrayReindexed;
}
$basearray = [1 => 17, 2 => 24, 3 => 12];
$test = addConstantToArrayKeys($basearray, 19);
print '<pre>';
print_r($test);
print '</pre>';
Output:
Array (
[20] => 17
[21] => 24
[22] => 12
)
You could use something unreadable like this. It does not mutate existing array keys.
<?php
$nums = [
1 => 17,
2 => 24,
3 => 12
];
$out = array_combine(array_map(
function($int) {
return $int + 10;
}, array_keys($nums)), $nums);
var_export($out);
Output:
array (
11 => 17,
12 => 24,
13 => 12,
)
Your first example is perfectly functional and readable, but for the naming.
<?php
$nums = [
1 => 17,
2 => 24,
3 => 12
];
$add_num_to_keys = function (array $in, $num) {
$out = [];
foreach($in as $k => $v)
$out[$k + $num] = $v;
return $out;
};
$out = $add_num_to_keys($nums, 10);
var_export($out);
Output:
array (
11 => 17,
12 => 24,
13 => 12,
)
You can't do:
foreach($in as &$k => $v)
$k += 10;
As the key element can't be a reference.
<?php
$quantity = array(1,2,3,4,5,6,7,8,9,10,11,12,1,14,2,16);
// Create a new array
$output_array = array();
$sum_quantity = 0;
$i = 0;
foreach ($quantity as $value) {
if($sum_quantity >= 35) {
$output_array[$i][] = $value;
}
$sum_quantity = $sum_quantity + $value;
}
print_r($output_array);
When summmary each item >= 35 will auto create child array
array(
[0] => array(1, 2, 3, 4, 5, 6, 7),
[1] => array(8, 9, 10),
[2] => array(11, 12, 1),
[3] => array(14, 2, 16)
)
$quantity = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 14, 2, 16);
// Create a new array
$output_array = array();
$current_array = array();
$current_sum = 0;
foreach ($quantity as $value) {
$current_sum += $value;
if ($current_sum >= 35) {
$output_array[] = $current_array;
$current_array = array();
$current_sum = $value;
}
$current_array[] = $value;
}
$output_array[] = $current_array;
print_r($output_array);
// Output:
// Array
// (
// [0] => Array
// (
// [0] => 1
// [1] => 2
// [2] => 3
// [3] => 4
// [4] => 5
// [5] => 6
// [6] => 7
// )
// [1] => Array
// (
// [0] => 8
// [1] => 9
// [2] => 10
// )
// [2] => Array
// (
// [0] => 11
// [1] => 12
// [2] => 1
// )
// [3] => Array
// (
// [0] => 14
// [1] => 2
// [2] => 16
// )
// )
I see,maybe your desired answer is as follows,
$quantity = array(1,2,3,4,5,6,7,8,9,10,11,12,1,14,2,16);
// Create a new array
$output_array = array();
$sum_quantity = 0;
$i = 0;
for each($quantity as $value) {
$sum_quantity += $value;
if($sum_quantity >= 35) {
$i++;
$output_array[$i][] = $value;
$sum_quantity = $value;
}else{
$output_array[$i][] = $value;
}
}
print_r($output_array);
I have tried test,It's ok.