Create an array with duplicated value from an array (PhP) - php

I want to create an new array with duplicated MAX value from an array
and put other duplicate value in an other array
$etudiant = array ('a'=>'2','b'=>'5', 'c'=>'6', 'd'=>'6', 'e'=>'2');
and i want this result
$MaxArray = array ('c'=>'6', 'd'=>'6');
$otherarray1 = array ('a'=>'2', 'e'=>'2');
Thank you !

First, find the maximum value:
$etudiant = array ('a'=>'2','b'=>'5', 'c'=>'6', 'd'=>'6', 'e'=>'2');
$maxValue = max($etudiant);
Second, find values that appear more than once:
$dups = array_diff_assoc($etudiant, array_unique($etudiant));
Lastly, check the original arrays for values matching either $maxValue or values that are listed in $dups:
$MaxArray = $OtherArray = $ElseArray = array();
foreach ($etudiant as $key => $value) {
if ($value == $maxValue) {
$MaxArray[$key] = $value;
} else if (in_array($value, $dups)) {
$OtherArray[$key] = $value;
} else {
$ElseArray[$key] = $value;
}
}
You'll get:
$MaxArray: Array
(
[c] => 6
[d] => 6
)
$OtherArray: Array
(
[a] => 2
[e] => 2
)
Note: I wasn't sure if you wanted the $MaxArray to contain the maximum value elements only if it appears more than once in the source array. If so, just change the max call to:
$maxValue = max($dups);

You can use array_values(array_intersect($array1, $array2)) to get duplicated values, and then make a loop to capture the keys which have those values and store them into another array.
$dups = array_values(array_intersect($array1, $array2))
$max = max($dups);
$result = array();
foreach ($array1 as $key => $value){
if (in_array($value, $dups)) {
$result[$key] = $value;
}
}
foreach ($array2 as $key => $value){
if (in_array($value, $dups)) {
$result[$key] = $value;
}
}
$maxArray = array();
foreach ($dups as $key => $value) {
if ($value == $max){
$maxArray[$key] = $value;
}
}
// results are in $dups and $maxArray

If you are looking to find elements with the min and max values from an array, the following will work.
// get min keys
$min_value = min($etudiant);
$min_keys = array_keys($etudiant, $min_value);
// get max keys
$max_value = max($etudiant);
$max_keys = array_keys($etudiant, $max_value);
You could then either rebuild your example arrays with these keys in a loop. Or access them directly, i.e. $etudiant[$min_keys].
Check out the documentation for array_keys, min, max

Related

Rank array values with possible duplicate values

I am trying to rank an array of values and maintain the order in the original array.
So for example:
(6,4,7,12,7) should return (2,1,3,4,3)
(12,17,5,27,5) should return (2,3,1,4,1)
(1,1,4,6) should return (1,1,2,3)
In each case the returned array has the rank of the corresponding element in the original array, and duplicate values will have the same rank.
$values = array(12,17,5,27,5);
$sorted_values = $values;
sort($sorted_values);
foreach ($values as $key => $value) {
foreach ($sorted_values as $sorted_key => $sorted_value) {
if ($value == $sorted_value) {
$rank_key = $sorted_key;
break;
}
}
echo $value . ' has rank: ' . $rank_key + 1 . '<br>';
}
A simple way would be to first rank the unique values (using array_unique() followed by sort()), then translate the original list by this newly rank list (more comments in the code)...
$source = [12,17,5,27,5];
$output = [];
// Copy to work array unique values
$rank = array_unique($source);
// Sort it to produce ranking order
sort($rank);
// Make the number the key with the order as the value
$rank = array_flip($rank);
// Translate the values using $rank
foreach ( $source as $element ) {
$output[] = $rank[$element]+1;
}
print_r($output);
gives...
Array
(
[0] => 2
[1] => 3
[2] => 1
[3] => 4
[4] => 1
)
Clone your array, sort the clone by values, while keeping the key associations.
Loop over the clone, and in classical “control break” fashion, compare the value of the current item to that of the previous one. Increase the rank by one, if they differ. Set that rank as new value under that key.
Sort the clone by keys.
$data = [12,17,5,27,5];
$clone = $data;
asort($clone);
$rank = 0;
$previous_value = null; // something that doesn't ever occur in your array values
foreach($clone as $key => $value) {
if($value !== $previous_value) {
$rank++;
}
$clone[$key] = $rank;
$previous_value = $value;
}
ksort($clone);
var_dump($data, $clone);
you need to sort your array
This may close to your answer:
<?php
$my_array=array(12,17,5,27,5);
$ordered_values = $my_array;
$rank=array();
rsort($ordered_values);
foreach ($ordered_values as $key => $value) {
foreach ($ordered_values as $ordered_key => $ordered_value) {
if ($value === $ordered_value) {
$key = $ordered_key;
break;
}
}
$rank[$value]=((int) $key + 1) ;
}
foreach($my_array as $key => $value)
{
echo $value.':'.$rank[$value].'<br>';
}
?>
function rankDuplicateArray(array $array): array
{
$copy = array_unique($array);
sort($copy);
$flipArray = array_flip($copy);
return array_map(function($v) use ($flipArray) {
return $flipArray[$v] + 1;
}, $array);
}

how to insert array 2d in table mysql with php if sub array diferent

i will ask how to insert array if amount sub arrays not same, i have problem if the $arrays != 3 because in sub arrays 2 in arrays one
<?php
$arrays=array(
array('a','b'),
array('a','b','c'),
array('a','b','c')
);
$per=0;
for ($h=0; $h < count($arrays); $h++) {
if (count($arrays) > $per) {
$per= count($arrays);
}
}
$koneksi = new mysqli("127.0.0.1","root","","data");
$nil=array();
foreach ($arrays as $data) {
foreach ($data as $key => $value) {
$data[$key] = $data[$key];
}
$nil[]="('".implode("', '",$data). "')";
}
$insert="INSERT INTO datams (data1,data2,data3) VALUES ".implode(', ',$nil);
$queri=mysqli_query($koneksi, $insert);
if ($queri == true){
echo 'upload done'.PHP_EOL;
} else {
echo 'fail upload'.PHP_EOL;
}
i can't insert the data if sub array same, can help me ?
You will have to make the arrays the same length.
Create an empty array, then loop your existing array, adding the missing values using array_replace. After that, you can insert them.
$empty=['' , '' , ''];
foreach($array as $key => $tmp){
$array[$key] = array_replace($empty,$tmp);
// This replaces the values of $empty with those of $array that are set:
// ['','',''] replace wihh ['a','b','c'] gives ['a','b','c']
// ['','',''] replace with ['a','b'] gives ['a','b','']
}
You will end up with:
$arrays=array(
array('a','b','' ),
array('a','b','c'),
array('a','b','c')
);
Now you can insert the values;
EDIT
To make it more flexible (i.e the original array keeps changing), you first have to find the length of the longest array in $array.
$max=0;
foreach($array as $a) {
$c = count($a);
if( $c > $max) $max = $c;
}
$empty=array_fill(0,$max,'');

Compare and replace values in array

I need compare 2 arrays , the first array have one order and can´t change , in the other array i have different values , the first array must compare his id with the id of the other array , and if the id it´s the same , take the value and replace for show all in the same order
For Example :
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
The Result in this case i want get it´s this :
"1a-dogs","2a-cats","3a-birds","4a-walking"
If the id in this case 4a it´s the same , that entry must be modificate and put the value of other array and stay all in the same order
I do this but no get work me :
for($fte=0;$fte<count($array_1);$fte++)
{
$exp_id_tmp=explode("-",$array_1[$fte]);
$cr_temp[]="".$exp_id_tmp[0]."";
}
for($ftt=0;$ftt<count($array_2);$ftt++)
{
$exp_id_targ=explode("-",$array_2[$ftt]);
$cr_target[]="".$exp_id_targ[0]."";
}
/// Here I tried use array_diff and others but no can get the results as i want
How i can do this for get this results ?
Maybe you could use the array_udiff_assoc() function with a callback
Here you go. It's not the cleanest code I've ever written.
Runnable example: http://3v4l.org/kUC3r
<?php
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
function getKeyStartingWith($array, $startVal){
foreach($array as $key => $val){
if(strpos($val, $startVal) === 0){
return $key;
}
}
return false;
}
function getMergedArray($array_1, $array_2){
$array_3 = array();
foreach($array_1 as $key => $val){
$startVal = substr($val, 0, 2);
$array_2_key = getKeyStartingWith($array_2, $startVal);
if($array_2_key !== false){
$array_3[$key] = $array_2[$array_2_key];
} else {
$array_3[$key] = $val;
}
}
return $array_3;
}
$array_1 = getMergedArray($array_1, $array_2);
print_r($array_1);
First split the 2 arrays into proper key and value pairs (key = 1a and value = dogs). Then try looping through the first array and for each of its keys check to see if it exists in the second array. If it does, replace the value from the second array in the first. And at the end your first array will contain the result you want.
Like so:
$array_1 = array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2 = array("4a-walking","2a-cats");
function splitArray ($arrayInput)
{
$arrayOutput = array();
foreach ($arrayInput as $element) {
$tempArray = explode('-', $element);
$arrayOutput[$tempArray[0]] = $tempArray[1];
}
return $arrayOutput;
}
$arraySplit1 = splitArray($array_1);
$arraySplit2 = splitArray($array_2);
foreach ($arraySplit1 as $key1 => $value1) {
if (array_key_exists($key1, $arraySplit2)) {
$arraySplit1[$key1] = $arraySplit2[$key1];
}
}
print_r($arraySplit1);
See it working here:
http://3v4l.org/2BrVI
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
function merge_array($arr1, $arr2) {
$arr_tmp1 = array();
foreach($arr1 as $val) {
list($key, $val) = explode('-', $val);
$arr_tmp1[$key] = $val;
}
foreach($arr2 as $val) {
list($key, $val) = explode('-', $val);
if(array_key_exists($key, $arr_tmp1))
$arr_tmp1[$key] = $val;
}
return $arr_tmp1;
}
$result = merge_array($array_1, $array_2);
echo '<pre>';
print_r($result);
echo '</pre>';
This short code works properly, you'll get this result:
Array
(
[1a] => dogs
[2a] => cats
[3a] => birds
[4a] => walking
)

php dictionary-style array and sort by specific key name

I have a foreach construct:
foreach($_POST as $name => $value) {
if($value && $value > 0){ // ensure we have a positive amount
$composite = explode("-", Replace($name, "ScheduleID_", ""));
$scheduleID = $composite[0];
$thisUserID = $composite[1];
$payPalEmail = $composite[2];
$amount = $value;
$counter++;
$sum += $value;
}
}
I'm getting correct values in all my variables. Inside the foreach I need to construct an array containing these 4 values:
$scheduleID
$thisUserID
$payPalEmail
$amount
...and then sort the array by $thisUserID. And then I need to know how to build the foreach to correctly iterate the new array and grab each of my values.
IMPORTANT: Every $scheduleID will be unique, but the other 3 values will sometimes repeat.
I was thinking something like this, but can't get it to work right:
$object["ScheduleID"] = $scheduleID
$object["UserID"] = $thisUserID
$object["PayPalEmail"] = $payPalEmail
$object["Amount"] = $amount
(and then perform the sort on $object["UserID"]) - I have tried different sort schemes from stackoverflow and php docs, but I must be doing something wrong.
Thanks in advance.
You can just prepare array in foreach like this:
foreach($_POST as $name => $value) {
if($value && $value > 0){ // ensure we have a positive amount
$composite = explode("-", Replace($name, "ScheduleID_", ""));
$objects[$composite[0]] = array(
'UserID' => $composite[1],
'payPalEmail' => $composite[2]
);
$amount = $value;
$counter++;
$sum += $value;
}
}
ksort($objects);
Then after foreach You can sort array by ksort.

php array keys problem

I have the following code:
$rt1 = array
(
'some_value1' => 'xyz1',
'some_value2' => 'xyz2',
'value_1#30'=>array('0'=>1),
'value_2#30'=>array('0'=>2),
'value_3#30'=>array('0'=>3),
'value_1#31'=>array('0'=>4),
'value_2#31'=>array('0'=>5),
'value_3#31'=>array('0'=>6),
'some_value3' => 'xyz3',
'some_value4' => 'xyz4',
);
$array_30 = array
(
'0'=>1,
1=>'2',
2=>'3'
);
$array_31 = array
(
'0'=>4,
'1'=>'5',
'2'=>'6'
);
I need to make it an array and insert the array_30 and array_31 into a DB.
foreach($rt1 as $value){
$rt2[] = $value['0'];
}
The question was updated, so here is an updated answer. Quick check, you should really try and update this to whatever more generic purpose you have, but as a proof of concept, a runnable example:
<?php
$rt1 = array
(
'some_value1' => 'xyz1',
'some_value2' => 'xyz2',
'value_1#30'=>array('0'=>1),
'value_2#30'=>array('0'=>2),
'value_3#30'=>array('0'=>3),
'value_1#31'=>array('0'=>4),
'value_2#31'=>array('0'=>5),
'value_3#31'=>array('0'=>6),
'some_value3' => 'xyz3',
'some_value4' => 'xyz4',
);
$finalArrays = array();
foreach($rt1 as $key=>$value){
if(is_array($value)){
$array_name = "array_".substr($key,-2);
${$array_name}[] = $value['0'];
}
}
var_dump($array_30);
var_dump($array_31);
?>
will output the two arrays with the numbers 1,2,3 and 4,5,6 respectivily
i assume you want to join the values of each of the second-level arrays, in which case:
$result = array();
foreach ($rt1 as $arr) {
foreach ($arr as $item) {
$result[] = $item;
}
}
Inspired by Nanne (which reminded me of dynamically naming variables), this solution will work with every identifier after the \#, regardless of its length:
foreach ( $rt1 as $key => $value )
{
if ( false == strpos($key, '#') ) // skip keys without #
{
continue;
}
// the part after the # is our identity
list(,$identity) = explode('#', $key);
${'array_'.$identity}[] = $rt1[$key]['0'];
}
Presuming that this is your actual code, probably you will need to copy the array somewhere using foreach and afterwards create the new array as you wish:
foreach($arr as $key => $value) {
$arr[$key] = 1;
}

Categories