Reading sorted array - php

Why $val is Array(1), but not the numeric value? I expected that $selected as $k => $val should return each line from the array $selected. Thus, $k must be a numeric key (it is) and $val must be corresponding numeric value (but it's an array instead of simple integer).
So, how do I correctly save sorted keys and values in array $ind and $ranks?
<?php
$selected = array();
for ($i=0; $i<5; $i++) {
$selected[] = array($i => rand(0,5));
}
arsort($selected);
$ind = array();
$rank = array();
foreach($selected as $k => $val) {
$ind[] = $k;
$rank[] = $val;
}
?>
UPDATE:
For incstance, this code..
for ($i=0; $i<5; $i++) {
$selected[$i] = rand(0,5);
}
provided the array:
[0] => 5, [1] => 3, [2] => 2, [3] => 5, [4] => 3
Once I sorted it, initial keys are deleted, right? How can I find initial keys [0]-[4] of randomly generated values after sorting the array?

I think your likely solution is to change
$selected[] = array($i => rand(0,5));
to
$selected[] = rand(0,5);
Doing so will yield $ind and $rank like this:
Array
(
[0] => 0
[1] => 3
[2] => 2
[3] => 4
[4] => 1
)
Array
(
[0] => 4
[1] => 3
[2] => 1
[3] => 0
[4] => 0
)
The best way to do what you want, is to just use the resultant array, for example:
$selected
Array
(
[1] => 5
[2] => 5
[4] => 4
[0] => 2
[3] => 1
)

I think this is what you need
for ($i=0; $i<5; $i++) {
$selected[$i] = rand(0,5);
}

Your array structure will look like this:
array(
0 => array(0 => 1),
1 => array(1 => 4),
...
)
because you're assigning an array here:
$selected[] = array($i => rand(0,5));
You just want this instead:
$selected[] = rand(0,5);

Hi I am not pretty much sure what you are trying to do but following code is creating an array of arrays.
$selected = array();
for ($i=0; $i<5; $i++) {
$selected[] = array($i => rand(0,5));
}
So $val will be an array. You can try following code:
$selected = array();
for ($i=0; $i<5; $i++) {
$selected[] = rand(0,5);
}
Thanks

Related

How to move values from 2nd array into the empty places of 1st array

How to move values from 2nd array into the empty places of 1st array
1st array as below
Array
(
[0] => 1
[1] =>
[2] => 4
[3] =>
)
2nd array as below
Array
(
[0] => 5
[1] => 9
)
I want output as merging 2nd array into 1st as shown below
Array
(
[0] => 1
[1] => 5
[2] => 4
[3] => 9
)
I have tried below code.....
for($i=0; $i<$count; $i++){
for($j=$i; $j<=$i; $j++)
if(empty($assign_taskk[$i])){
$assign_taskk[$i] = $taskkk[$i];
}
}
plz help me out for same
Lets say your arrays look like:
$a1 = [
0 => 1,
1 => null,
2 => 4,
3 => null,
];
$a2 = [
0 => null,
1 => 5,
2 => null,
3 => 9,
];
Then you can iterate over first array and add values from the second one when needed:
foreach ($a1 as $k => $v) {
if (empty($v) && !empty($a2[$k])) {
$a1[$k] = $a2[$k];
}
}
Another way to do it using below way-
<?php
$arr1= [1,null,4,null];
$arr2 = [null,5,null,9];
$result = array_values(array_filter($arr1) + array_filter($arr2));
print_r($result)
?>
DEMO: https://3v4l.org/R4aeE
Hi #amod try this
$_newArray = array_values(array_filter($array1) + array_filter($array2));
print_r($_newArray);
You can use below code for this:
$firstArray = [1,'',4,''];
$secondArray = [5,9];
$secondArrayCounter = 0;
foreach($firstArray as $key => $value) {
if (empty($value)) {
$firstArray[$key] = $secondArray[$secondArrayCounter];
$secondArrayCounter++;
}
}
print_r($firstArray);
Hope it helps you.

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

Last value condition foreach in array?

I have an array like that:
[0] => Array
(
[sendby] => 3
[refresh] => 0
[last] => 0
)
[1] => Array
(
[sendby] => 3
[refresh] => 1
[last] => 1
)
[2] => Array
(
[sendby] => 8
[refresh] => 1
[last] => 1
)
I want the value last to be 1 when the value sendby (here 3 and 8) is the last of the entire array! How can I do that?
Get the last 2 value and compare with array [3,8]
// get array of sendby values
$temp = array_column($array, 'sendby');
// get array with two last values
$temp = array_slice($temp, -2);
// Check
if ($temp == [3,8]) {
$value = 1;
}
else {
$value = 0;
}
or in one line
$value = array_slice(array_column($array, 'sendby'), -2) == [3,8] ? 1 : 0;
demo
Update on base of comments
// get array with two last values
$temp = array_slice(array_column($array, 'sendby'), -2);
foreach($array as &$x) {
// If current send by is in $temp array
if(in_array($x['sendby'], $temp)) {
$x['last'] = 1;
}
else {
$x['last'] = 0;
}
}
print_r($array);
You can use an array to assist the existing ocurrences of that id. I have an working example (Tested on php sandbox):
$array = array(
0 => array
(
'sendby' => 3,
'refresh' => 0,
),
1 => array
(
'sendby' => 3,
'refresh' => 1,
),
2 => array
(
'sendby' => 8,
'refresh' => 1,
)
);
$ocurrences = [];
foreach($array as $key => $elem ){
$id = $elem['sendby'];
if (isset($ocurrences[$id])) {
$array[$ocurrences[$id]]['last'] = 0;
$array[$key]['last'] = 1;
$ocurrences[$id] = $key;
} else {
$ocurrences[$id] = $key;
$array[$key]['last'] = 1;
}
}
echo print_r($array, 1);
The result:
Array
(
[0] => Array
(
[sendby] => 3
[refresh] => 0
[last] => 0
)
[1] => Array
(
[sendby] => 3
[refresh] => 1
[last] => 1
)
[2] => Array
(
[sendby] => 8
[refresh] => 1
[last] => 1
)
)
Basically I used an array with the ocurrences of the 'sendby' index of the array. The $occurences array has the elements with the key of the last checked element.
Lets suppose your array is $array;
You could iterate through it and if it's the last element, then set [last] to 1, else set to 0;
Try to run the below code after your array is populated.
$i =1;
foreach($array as $ar) {
$ar->last = ($i == count($array) && ($ar->sendby == 3 || $ar->sendby == 8)) ? 1 : 0;
$i++;
}
$count = count($arr) ;
$i = 0;
foreach($arr as $key=>$val) {
if(++$I === $count) {
echo "last element" ;
}
}

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

Cannot modify multidimensional array PHP

I have two arrays.
First one ($dcel) looks like this:
Array(
[1] => Array
(
[V1] => 5
[V2] => 2
[F1] => 4
[F2] => 1
[P1] => 7
[P2] => 4
)
etc..
Second one ($PctOldNew) looks like this:
Array(
[0] => Array
(
[old] => 1
[new] => 3
)
etc..
I'm trying to find the 'old' values (which are the initial) in the first array. Here's my code:
foreach ($dcel as $latura) {
for($i = 0; $i <= $nrPct; $i++){
if($PctOldNew[$i]['old'] == $latura[V1]){
$latura[V1] = $PctOldNew[$i]['new'];
}
}
}
If I output the $PctOldNew inside if statment, the output it's the correct answer, but if i try to modify $latura[V1] the $dcel remains untouched.
I've tried with reference, keys... but nothing works and i can't see what's wrong.
This works:
edit: adding a 2nd array element to $dcel to show how it works
<?php
$dcel = Array(
'1' => Array
(
'V1' => 1, // <-- note that i changed this value from your original '5' to '1' so that your condition will actually match something, since this example data set doesn't actually have something to match
'V2' => 2,
'F1' => 4,
'F2' => 1,
'P1' => 7,
'P2' => 4
)
'2' => Array
(
'V1' => 5,
'V2' => 2,
'F1' => 4,
'F2' => 1,
'P1' => 7,
'P2' => 4
)
);
$PctOldNew = Array(
'0' => Array
(
'old' => 1,
'new' => 3
)
);
foreach ($dcel as &$latura) { // <-- reference on &$latura
for($i = 0; $i <= $nrPct; $i++){
if($PctOldNew[$i]['old'] == $latura['V1']){
$latura['V1'] = $PctOldNew[$i]['new'];
}
}
}
echo "<pre>";print_r($dcel);
output
Array
(
[1] => Array
(
[V1] => 3
[V2] => 2
[F1] => 4
[F2] => 1
[P1] => 7
[P2] => 4
)
[2] => Array
(
[V1] => 5
[V2] => 2
[F1] => 4
[F2] => 1
[P1] => 7
[P2] => 4
)
)
#CrayonViolent it didn't work, i tried so many times.
I was playing right now with the code and it seems that like this it's working:
foreach ($dcel as $key => $value) {
foreach ($value as $val) {
for($i = 0; $i <= $nrPct; $i++){
if($PctOldNew[$i]['old'] == $value[V1])
$new = $PctOldNew[$i]['new'];
}
$val = $new;
}
$dcel[$key][V1] = $val;
}
...but i don't know why.
The most convenient way in your case would be using array_map() function
Like this:
$array = array(1,2,3,4,5);
$replacements = array(
array('old'=>1, 'new'=>11),
array('old'=>3, 'new'=>33),
);
$array = array_map(function($element){
global $replacements;
foreach($replacements as $r) if($r['old']==$element) return $r['new'];
return $element;
}, $array);
print_r($array);
Result:
Array ( 11, 2, 33, 4, 5 )
Another weird way is to use array_walk
array_walk(&$dcel, function($latura){
for($i = 0; $i <= $nrPct; $i++){
if($PctOldNew[$i]['old'] == $latura[V1]){
$latura[V1] = $PctOldNew[$i]['new'];
}
}
});
Or array_map
$dcel = array_map(function($latura){
for($i = 0; $i <= $nrPct; $i++){
if($PctOldNew[$i]['old'] == $latura[V1]){
$latura[V1] = $PctOldNew[$i]['new'];
}
}
return $latura;
}, $dcel);
(Not sure why array_walk and array_map have reversed parameter position)
Updated with the real reason and 2 more possible solutions
The reason you can't modify $latura is because you are using for...each loop which will pass $latura by-value rather than by-reference. Based on this reason, you have 2 more solutions,
Use for $dcel as $key => $latura then you can change $dcel[$key]
Use for $dcel as &$latura then you can change the item directly

Categories