Sort an array based on values from another array - php

I have an array which i would like to sort it based on values from another one.
FIrst array:
$array1 = ( '2' , [val]->'3' , [val1]->'1')
And second one:
$array2 = (1,4,3)
I've tried a bubble sort but does not work:
for ($i = 1 ; $i <= $array1[0] ; $i++){
for ($j = $i+1 ; $j <= $array1[0] ; $j++){
if ($array2[$i] < $array2[$j]){
$temp = $array1[$i];
$array1[$i] = $array1[$j];
$array1[$j] = $temp;
}
}
}

use usort(), it allowes you to give user defined function to sort..
Documentation..

Related

Rearrange php array, move one value from one spot to another spot in array

$array = [
"2a15108c-b20d-4025-ad92-3ebfb3bb7970",
"3a088dcd-160b-44e4-8286-f22be7703ab7",
"5a088dcd-160b-44e4-8286-f22be7703a41",
"9a088dcd-160b-44e4-8286-f22be7703a6f",
"65a31a98-6666-4cb6-8a47-2b80a9c914d8",
];
I have an array, I want to move "9a088dcd-160b-44e4-8286-f22be7703a6f" from 4th in the array, to 2nd, so the expected output would be:
$array = [
"2a15108c-b20d-4025-ad92-3ebfb3bb7970",
"9a088dcd-160b-44e4-8286-f22be7703a6f",
"3a088dcd-160b-44e4-8286-f22be7703ab7",
"5a088dcd-160b-44e4-8286-f22be7703a41",
"65a31a98-6666-4cb6-8a47-2b80a9c914d8",
];
I tried looping thru, once I found "9a088dcd-160b-44e4-8286-f22be7703a6f", I'd unset it, then array_values
array_values($uuids);
Then add "9a088dcd-160b-44e4-8286-f22be7703a6f" to the array, since I want it to be third in the list, I need to make sure it gets added after the 2nd one in the list
$uuids[1] = "9a088dcd-160b-44e4-8286-f22be7703a6f";
Which then removes: 2a15108c-b20d-4025-ad92-3ebfb3bb7970
from the array
I need to keep 2a15108c-b20d-4025-ad92-3ebfb3bb7970 and add 9a088dcd-160b-44e4-8286-f22be7703a6f after it
Use array_splice() to remove and insert from the array.
$removed = array_splice($array, 4, 1);
array_splice($array, 2, 1, $removed);
Note that if you're moving to an index later than the original index, you'll need to subtract 1 from the destination index to adjust for the fact that the element was removed and all indexes shifted down.
The way I see it is to pull up or down the elements in between and then add your search value at the desired position.
Snippet:
<?php
function reArrange(&$array, $searchVal, $newPosition){
for($i = 0; $i < count($array); $i++){
if($array[ $i ] === $searchVal){
if($i > $newPosition){
for($j = $i - 1; $j >= $newPosition; --$j){
$array[ $j + 1] = $array[ $j ];
}
}else{
for($j = $i; $j < $newPosition; ++$j){
$array[ $j ] = $array[ $j + 1 ];
}
}
$array[$newPosition] = $searchVal;
break;
}
}
}
Online Demo

Sum each row of a multidimensional array

I want to sum each row of a multidimensional array :
$number = array
(
array(0.3,0.67, 0.3),
array(0.3,0.5,1),
array(0.67,0.67,0.3),
array(1,0.3,0.5)
);
The result what i want is like this :
row1 = 1.27
row2 = 1.8
row3 = 1.64
row4 = 1.8
I already tried this code :
for($i = 0; $i < 4; $i++) {
for($j = 0; $j < 5; $j++) {
$sumresult[] = array_sum($number[$i][$j]);
}
}
But it appear an error like this :
Warning: array_sum() expects parameter 1 to be array, double given in xxxx
array_sum needs array not values. Do like this:
for($i = 0; $i < 4; $i++) {
$sumresult[] = array_sum($number[$i]);
}
its because you are passing an value instead of the array containing it.
One correct solution would be:
$sumResult = array();
foreach($number as $values){
$sumResult []= array_sum($values);
}
print_r($sumResult);
Should do the trick ;)
It's easier to just map the array_sum() function to the array to sum the inner arrays:
$sumresult = array_map('array_sum', $number);

How to merged 3 arrays in one line output in php [duplicate]

This question already has answers here:
Two arrays in foreach loop
(24 answers)
Closed 6 months ago.
Good Day!
Any suggestions on how can I merged and print 3 arrays in PHP.
I retrieved data from database and put it in ARRAY.
1st Array: $date[] = $row['date'];
2nd Array: $requestor[] = $row['requestor'];
3rd Array: $die[] = $row['die'];
then I use foreach to print the retrieved data stored from each Array that meets the condition.
foreach($date as $item_date){
echo $item_date;
}
foreach($requestor as $item_requestor){
echo $item_date;
}
foreach($die as $item_die){
echo $item_requestor;
}
But the result of this code is like this:
date1
date2
date3
requestor1
requestor2
requestor3
die1
die2
die3
My goal is this one:
date1 - requestor1 - die1
date2 - requestor2 - die2
date3 - requestor3 - die3
Any Idea oon how can I achieved this output.
TIA
You have to do it manually count on loop like this
$count = count($date)-1;
then loop through this
for ( $i=0;$i <= $count; $i++ ) {
$arrayGenerate[$i] = array(
'row1' => $data[$i].'-'.$requestor[$i].'-'.$die[$i]
);
}
like this
Try with -
for($i = 0; $i <= count($date); $i ++) {
echo $date[$i]." - ".$requestor[$i]." - ".$die[$i];
}
Assuming the all 3 arrays count/size is same & you want it in this fashion
<?php
$a = array('1','2','3');
$b = array('4','5','6');
$c = array('7','8','9');
for($i=0;$i<count($a);$i++)
{
echo $merged_arr_str = $a[$i] . " - " . $b[$i] . " - ". $c[$i] . " <br/>";
}
?>
You can try this
Example One:-
$date = array('date1','date2','date3','date4');
$requestor = array('requestor1','requestor2','requestor3','requestor4');
$die = array('die1','die2','die3','die4');
$count = max(count($date), count($requestor), count($die));
$newarray = array();
for($i=0; $i < $count; $i++) {
//Demo1
if (isset($date[$i])) $newarray[] = $date[$i];
if (isset($requestor[$i])) $newarray[] = $requestor[$i];
if (isset($die[$i])) $newarray[] = $die[$i];
//Demo2
//echo $ouput = $date[$i].'-'.$requestor[$i].'-'.$die[$i];
}
//array merge output
var_dump($newarray);
Example Two
$date = array('date1','date2','date3','date4');
$requestor = array('requestor1','requestor2','requestor3','requestor4');
$die = array('die1','die2','die3','die4');
$arrays = array($date, $requestor, $die);
array_unshift($arrays, null);
$n = call_user_func_array('array_merge', call_user_func_array('array_map', $arrays));
print_r($n);
for($i = 0; $i < count($date); $i ++) {
echo $date[$i]." - ".$requestor[$i]." - ".$die[$i];
}
this loop will iterat untill last element of date array.if you want to put equal to sign then you have to initialize $i with 1.
exm. if $i = 0 then $i < count($date)
OR
if $i = 1 then $i <= count($date)

PHP put several arrays in one separated by ","

I have some arrays extracted from a XML-file. These are in
$array0 = (.......)
$array1 = (.......)
...
$arrayN = (.......)
Now I need a single array with all arrays in it separated by "," as
$masterArray = array($array0,
$array1,
...
$arrayN)
I tried
for ( $i = 0; $i < N; $i++) {
$masterArray = $masterArray + $array[$i];
}
with no result. I tried array_merge but this will give one
$masterArray(......................all items of all $arrays.....)
How can I do it right?
for ( $i = 0; $i < N; $i++) {
$temp = "array".$i;
$masterArray[$i] = ${$temp};
}
Given your exact definition of what you got and what you want the routine should be:
for ( $i = 0; $i < N; $i++) $masterArray[] = ${'array'.$i};
Not much to explain here. You make a new entry in an array with $variable[] = <entry>; and you access your numbered array with a variable variable, see:
http://php.net/manual/en/language.variables.variable.php
I guess you wont to create a multi dimension array:
$masterArray = array();
$masterArray[] = $array0;
$masterArray[] = $array1;
...
$masterArray[] = $arrayN;
this will in all arrays as element of the MasterArray:
$masterArray[0=>(....),1=>(....), ...];
Then access it like this:
$arr1_key1 = $masterArray[1]['key1'] ; //$array1['key1'];
You can add specific keys if you wont:
$masterArray['arr1'] = $array1;
$arr1_key1 = $masterArray['arr1']['key1'] ; //$array1['key1']
In general read some more to get better understanding on how to work with arrays ;)

Sort an array of arrays based on values from another array

I have an array which i would like to sort it based on values from another one.
FIrst array:
$array1 = ( [0]=> Int(2)
[1]=>Array(['id']=>String(5) , ['value']=>String(10))
[2]=>Array(['id']=>String(5) , ['value']=>String(10))
[3]=>Array(['id']=>String(5) , ['value']=>String(10))
)
And second one:
$array2 = (1,4,3)
The result should be based on $array2:
$array1 = ( [0]=> Int(2)
[1]=>Array(['id']=>String(5) , ['value']=>String(10))
[3]=>Array(['id']=>String(5) , ['value']=>String(10))
[2]=>Array(['id']=>String(5) , ['value']=>String(10))
)
I've tried a bubble sort but does not work:
for ($i = 1 ; $i <= $array1[0] ; $i++){
for ($j = $i+1 ; $j <= $array1[0] ; $j++){
if ($array2[$i] < $array2[$j]){
$temp = $array1[$i];
$array1[$i] = $array1[$j];
$array1[$j] = $temp;
}
}
}
Have you tried checking array_multisort? You could inject array 2 into array 1 and then sort it that way?

Categories