PHP: How to reorder a two dimensional array - php

This is how $myArray looks like:
Array
(
[0] => Array
(
[month] => 1
[atual] => 0.00
)
[1] => Array
(
[month] => 2
[atual] => 11970.99
)
[2] => Array
(
[month] => 3
[atual] => 2888.00
)
[3] => Array
(
[month] => 5
[atual] => 1500.00
)
)
I want to "fill the gaps" of the months. That is, for those months, where we have no data (4,6,8,9,10,11,12), I want the [atual] to be zero.
I tried:
$novo=array();
for ($i=1; $i <=12 ; $i++) {
$mes=$myArray[$i-1]['month'];
$atual=$myArray[$i-1]['atual'];
if(!$mes){
$novo[$i]=0;
} else{
$novo[$i]=$atual;
}
};
But this is returning:
Array
(
[1] => 0.00
[2] => 11970.99
[3] => 2888.00
[4] => 1500.00
[5] => 0
[6] => 0
[7] => 0
[8] => 0
[9] => 0
[10] => 0
[11] => 0
[12] => 0
)

[edit] now i see you have another problem, your $myArray indexes aren't matching the months.
$myArray(
array('month' => 1, 'atual' => 0.00),
array('month' => 2, 'atual' => 11970.99),
array('month' => 3, 'atual' => 2888.00),
array('month' => 5, 'atual' => 1500.00)
)
for($i = 1; $i <= 12; $i++){
$novo[$i] = 0;
}
foreach($myArray as $item){
$novo[$item['month']] = $item['atual'];
}
print_r($novo);

This worked:
$novo=array_fill(1,12,0);
for ($i=1; $i <=12 ; $i++) {
$mes=$myArray[$i-1]['month'];
$atual=$myArray[$i-1]['atual'];
$novo[$mes]=$atual;
};

With this code you get the month 1 in position 1 (not in position 0);
Also you only search in the array one time.
It's not a beautiful solution but...
$my_array = array(
array('month'=>3,'actual'=>100)
);
$results =array();
for($i=1;$i<13;$i++){
$results[$i] = 0;
}
foreach($my_array as $a){
$results[$a['month']] = $a['actual'];
}
print_r($results);

PHP has several functions that deal with sorting arrays, and here is a comparison of array's sorting functions

I didn't fully understand your question in the first response. This code should work for you. First we will create a temporary array just to hold the month and the data in an accessible format. Then we create your array :
$temp=array();
// Populate the temp array
foreach ($myArray as $row) {
if (is_array($row) && isset($row["month"])) {
$temp[$row["month"]] = $row["atual"];
}
}
// Create novo array
for ($i=0; $i <12 ; $i++) {
$novo[$i]["month"] = $i+1;
if (array_key_exists($i+1, $temp)) {
$novo[$i]['atual'] = $temp[$i+1];
} else {
$novo[$i]['atual'] = 0;
}
}

Related

PHP Array Swap in dynamic input

I have two dynamic arrays of integer, one thing that I wanna do is swap value inside my array-based on input.
For example my two arrays:
$myArray_a =
Array
(
[0] => 21306000
[1] => 50627412
[2] => 2560227681
[3] => 2796924085
[4] => 0
[5] => 0
)
$myArray_b =
Array
(
[0] => 505909732
[1] => 400831144
[2] => 2693575413
[3] => 3072271817
[4] => 5277000763
[5] => 4944000763
)
And my expected output was when the input = 3, array B index number 4 and 5 swap to array A in the same index.
$output =
Array
(
[0] => 21306000
[1] => 50627412
[2] => 2560227681
[3] => 2796924085
[4] => 5277000763
[5] => 4944000763
)
I want to switch, is there an easy way to do this? Or will it require a loop + creating a new array?
Provided your are using an numeric index, you could leverage array_slice
This will create an array with the first four entries, then append the second array skipping existing keys.
$count = 4; // which is 3 + 1
$a = [21306000,50627412,2560227681,2796924085,0,0];
$b = [505909732,400831144,2693575413,3072271817,5277000763,4944000763];
$output = array_slice( $a, 0, $count ) + $b;
//Array
//(
// [0] => 21306000
// [1] => 50627412
// [2] => 2560227681
// [3] => 2796924085
// [4] => 5277000763
// [5] => 4944000763
//)
You can do it with,
$index = 3;
$result = $B;
for($i = 0; $i<= $index; $i++){
$result[$i] = $A[$i];
}
You can use foreach
foreach($myArray_a as $k => &$v){
empty($v) && isset($myArray_b[$k]) ? ($v = $myArray_b[$k]) : '';
}
DEMO :- https://3v4l.org/nRj68
<?php
$a = [2,3,4,5,0,0];
$b = [20,30,40,50,60,70];
$counter = 0;
$out = array_map(function($m, $n ) use (&$counter)
{
return $counter++>3 ? $n : $m;
}, $a, $b);
var_export($out);
Output:
array (
0 => 2,
1 => 3,
2 => 4,
3 => 5,
4 => 60,
5 => 70,
)

How to put all the sub array values in php variables

I'd like to add all the values from each sub arrays below in some distinct php variables.
I can access each value individually but I can't figure out how to put all the values from the first sub array in one variable e.g. $subarray_zero and all the values from the second sub array in another variable e.g. $subarray_one. The idea is then to use those variables to add the values in mysql, so I'll have two columns, one with all the values from the variable $subarray_zero and another column $subarray_one with all the values from the second sub array.
Array
(
[0] => Array
(
[5] => 3.5
[6] => 4.5
[7] => 5.5
)
[1] => Array
(
[8] => 5
[9] => 6
[10] => 7
)
)
Thanks for your help
full code
$period = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15);
$sma = array(6,9);
foreach ($sma as $range) {
$sum = array_sum(array_slice($period, 0, $range));
$result = array($range - 1 => $sum / $range);
for ($i = $range, $n = count($period); $i != $n; ++$i) {
$result[$i] = $result[$i - 1] + ($period[$i] - $period[$i - $range]) / $range;
}
$array[] = $result;
}
echo '<pre>';
print_r($array);
echo '</pre>';
$smplarr=Array(0 => Array(5 => 3.5,6 => 4.5,7 => 5.5),1 => Array(8 => 5,9 => 6,10 => 7));
list($subarray_zero,$subarray_one)=$smplarr;
print_r($subarray_zero);echo "<br>";
print_r($subarray_one);
see output
Array ( [5] => 3.5 [6] => 4.5 [7] => 5.5 )
Array ( [8] => 5 [9] => 6 [10] => 7 )
Use list Thanks

Filling php array that has missing values

I've a series of arrays with values that goes from 1 to 5. Almost every array has missing values, some even dont have any values. My objective is to fill the missing values with 0. All those arrays are stored into a multidimensional array.
My array looks like:
Array
(
[1] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[2] => Array
(
[0] => 1
[1] => 5
)
[3] => Array
(
[0] => (this array has no values)
)
[4] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
etc...
)
How it should be:
Array
(
[1] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 0
[4] => 0
)
[2] => Array
(
[0] => 1
[1] => 0
[2] => 0
[3] => 0
[4] => 5
)
[3] => Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
[4] => 0
)
[4] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
etc...
)
Any help would be appriciated!
For each of your subarrays loop through the numbers 1 to 5, and if that value exists set its key to be one less than its value:
$newarray = array();
foreach($arr as $key => $subarr) {
for ($i = 1; $i <= 5; $i++) {
if (in_array($i, $subarr)) $newarray[$key][$i - 1] = $i;
else $newarray[$key][$i - 1] = 0;
}
}
Where $newarray is your output and $arr is your input array.
You may want to note that PHP does not truly do multidimensional arrays. It only allows you to relate 2 flat arrays together which is not true multidimensionality.
This does not work and will produce results described above.
$menu[1] = "My Training"; //not $menu[1][0]
$menu[1][1] = "To Do List";
$menu[1][2] = "Catalog";
$menu[1][3] = "Self-Report";
$menu[1][4] = "Completions";
$menu[2] = "Manager";
$menu[2][1] = "Direct Reports";
$menu[2][2] = "Incompletes";
$menu[2][3] = "Completions";
$menu[3] = "Instructor";
$menu[3][1] = "My Classes";
$menu[3][2] = "Printables";
$menu[3][3] = "Qualifications";
This does work.
$menu[1] = "My Training"; //not $menu[1][0]
$submenu[1][1] = "To Do List";
$submenu[1][2] = "Catalog";
$submenu[1][3] = "Self-Report";
$submenu[1][4] = "Completions";
$menu[2] = "Manager";
$submenu[2][1] = "Direct Reports";
$submenu[2][2] = "Incompletes";
$submenu[2][3] = "Completions";
$menu[3] = "Instructor";
$submenu[3][1] = "My Classes";
$submenu[3][2] = "Printables";
$submenu[3][3] = "Qualifications";
$submenu is only related to $menu through the first key number as there are no first dimension values to $submenu.
Something like this (array_pad() won't do the trick). $myArray is your source array. Completed array is returned in $result:
$result = array();
foreach( $myArray as $subKey=>$subArray ) {
for( $i=0; $i<5; $i++ ) {
if( isset( $subArray[$i] )) {
$result[$subKey][$i] = $subArray[$i];
} else {
$result[$subKey][$i] = 0;
}
}
}
Note, we do copy of the array. You cannot fill array in-place.
It's been many years since I wrote any PHP but something like this might do the trick I guess?
for($i = 0; $i < 5; $i++)
{
if(empty($myArray[$i])
{
$myArray[$i] = 0;
}
}

PHP Array numbers

Easy question, I filled my array the following way:
$options = range(1, 10);
This will result:
array
(
[0] => 1
[1] => 2
etc. etc.
)
This is not the result I want..
I need my array like this:
array
(
[1] => 1
[2] => 2
etc.
)
How to accomplish this easy task?
Maybe like this:
$options = range(0, 10);
unset($options[0]);
working example
<?php
for( $i = 1; $i <= 10; $i ++ ) {
$array[$i] = $i;
}
Voila. :)
if you want a one-liner instead of a for-loop like Berry suggested, just use array_combine:
$array = array_combine(range(1,10),range(1,10));
function myRange($start, $limit, $step)
{
$myArr = array();
foreach((array) range($start, $limit,$step) as $k => $v)
{
$myArr[$k+1] = $v;
}
return $myArr;
}
print_r(myRange(0, 100, 10));
?>
Result
------
Array
(
[1] => 0
[2] => 10
[3] => 20
[4] => 30
[5] => 40
[6] => 50
[7] => 60
[8] => 70
[9] => 80
[10] => 90
[11] => 100
)
Or just shift the array
foreach ( $array as $key => $val )
$result[ $key+1 ] = $val;

php split array between two values

i have an array like:
Array ( [0] => #!A1#DC [1] => #IMSR102.71/74.82 [2] => #HV50 [3] => #PR7/7/ [4] => #RX0 [5] => #ERN/1//0 [6] => #Q2 [7] => #!A1#DC [8] => #IMSR102.50/74.82 [9] => #HV40 [10] => #PR5/5/ [11] => #RX0 [12] => #ERN/1//1 [13] => #Q2 etc etc with hundreds o values
i get this array from a file (with the function file($filename) ) and i need to split it in many subarray.
"!A1#DC" this is the beginning of a series of values ​​that ends with #Q2 but the number of the values between the beginning and the end is not always the same and the only 2 values that are same are the two given ("!A1#DC" for the beginning and "#Q2" for the end)
how can i get somethings like this?
Array (
[0] => Array ( [0] => #!A1#DC [1] => #IMSR102.71/74.82 [2] => #HV50 [3] => #PR7/7/ [4] => #RX0 [5] => #ERN/1//0 [6] => #Q2 )
[1] => Array (
[1] => #!A1#DC [2] => #IMSR102.50/74.82 [3] => #HV40 [4] => #PR5/5/ [5] => #RX0 [6] => #ERN/1//1 [7] => #Q2 etc etc
could you please help me?
thanks
Loop through an array. When you meet starting value, store it's index. When you meet ending value, use array_slice() to extract the part between the last pair of starting and ending values, store this part into another array.
$source = array (
'#!A1#DC',
'#IMSR102.71/74.82',
'#HV50',
'#PR7/7/',
'#RX0',
'#ERN/1//0',
'#Q2',
'#!A1#DC',
'#IMSR102.50/74.82',
'#HV40',
'#PR5/5/',
'#RX0',
'#ERN/1//1',
'#Q2',
);
$dest = array();
$startValue = '#!A1#DC';
$endValue = '#Q2';
$startIndex = 0;
foreach ( $source as $index => $value ) {
if ( $value === $startValue ) {
$startIndex = $index;
} else
if ( $value === $endValue ) {
$dest[] = array_slice($source, $startIndex, $index - $startIndex + 1);
}
}
print_r($dest);
Basically you need to loop through each element of $input, collecting those within START and END elements into a separate array:
$input = array("#!A1#DC", "A", "B", "#Q2");
$values = array();
$current = 0;
define("START", "#!A1#DC");
define("END", "#Q2");
for ($i = 0; $i < count($input); $i++) {
if ($input[$i] == END) {
// Ignore any elements after this point until we see START
$current = null;
} else if ($input[$i] == START) {
// Create a new current collection array
$current = count($values);
$values[$current] = array();
} else {
// Store the value if we are collecting
if ($current !== null) {
$values[$current][] = $input[$i];
}
}
}

Categories