PHP Array Swap in dynamic input - php

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,
)

Related

php split array on change of value in column data

I am trying to split array data into multiple arrays based on change in data value at known position (column).
$input = array(
array(1,2,3),
array(4,5,3),
array(7,8,4),
array(9,10,4),
array(11,12,4)
);
Here column 3 changes values from 3 to 4
and expected result is to have 2 arrays
$out1 = array(array(1,2,3),array(4,5,3));
$out2 = array(array(7,8,4), array(9,10,4), array(11,12,4));
since number of rows are variable, cannot use array_chunk
since column 3 values are variable, cannot use array_filter
number of output arrays are also variable.
trying splice but failing...
You can use array_reduce to make new array, where index will be equal to last numbers in items
$new = array_reduce($input, function($c, $x) { $c[$x[2]][] = $x; return $c; }, [] );
$out1 = $new[3];
$out2 = $new[4];
demo
But if array is not sorted and you want to split at points of changing that number, the code can be
$i = -1;
$last = null;
$new = [];
foreach($input as $x) {
if ($x[2] != $last) {
$i++;
$last = $x[2];
}
$new[$i][] = $x;
}
demo
You can use split index with index of array,
$out1 = $out2 = [];
$splitIndex = 2;
foreach($input as $k => $v){
if($k < $splitIndex){
$out1[] = $v;
}else{
$out2[] = $v;
}
}
print_r($out1);
print_r($out2);
Working demo
Output:-
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array
(
[0] => 4
[1] => 5
[2] => 3
)
)
Array
(
[0] => Array
(
[0] => 7
[1] => 8
[2] => 4
)
[1] => Array
(
[0] => 9
[1] => 10
[2] => 4
)
[2] => Array
(
[0] => 11
[1] => 12
[2] => 4
)
)

array comparison using php

Code does not stop running.i need to compare the two arrays in order to match each string. two arrays with different sizes.
First array:
Array (
[0] => '+2+x=1'
[1] => '+x+2=1'
[2] => 'x+2=1'
[3] => '-1+2=7'
[4] => '+2-1=7'
[5] => '+x+27=3+2'
[6] => 'x+27=3+2'
[7] => 'x=3'
[8] => '+x=3'
)
Second array:
Array (
[0] => '+x+2=1'
[1] => '-1+2=7'
[2] => '+x+27=3+2'
[3] => '+x=3'
)
my current code: (first array = $step_1, second array = $arr_result)
$count1 = 0;
for ($k=0; $k < count($arr_result); $i++) {
for ($l=0; $l < count($step_1); $l++) {
if (strcmp($arr_result[$k],$step_1[$l]) == 0) {
$count1++;
echo "$k "."$l ".strcmp($arr_result[$k],$step_1[$l])."<br>";
}
}
}
thanks in advance.
Use the function array_intersect, it will return an array with the matching values of both arrays :
$array1 = ['foo', 'bar', 'abc'];
$array2 = ['foo', 123, 456, 789, 4654, 'abcdef'];
$matching_values = array_intersect($array1, $array2);
$matching_values will result in
Array
(
[0] => foo
)
Edit: Notice that in your FOR you use $k but you increment $i... That's why your code doesn't stop;
for ($k=0; $k < count($arr_result); $i++)

PHP: How to reorder a two dimensional array

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;
}
}

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 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