Add the same elements of an array in a recursive way - php

Hello my goal is to add the same values ​​in an array and remove the repeated values ​​then add the sum of these repeated values ​​in the same array in a repetitive way until all the elements of the array will be distinct.
I made this code but it does it just once, how to repeat this action several times until the good result? thanks
function magic($arr)
{
$result = array_filter(array_count_values($arr), function ($el) {
return $el > 1;
});
foreach ($result as $k => $val) {
$a[] = $k;
$b[] = $k * $val;
}
$c[] = array_merge(array_diff($arr, $a), $b);
return $c;
}
print_r(magic([5, 5, 8, 8, 10, 9,20, 7, 7]));//found:[10,9,20,10,16,14] excpected:[9,40,14,16]( stape to find result:[10,9,20,10,16,14]==>[20,9,20,16,14]==>[9,40,14,16])

You could try using an associative array ad add the same key
foreach ($result as $k => $val) {
$a[$k] = (isset($a[$k]) ? a[$k] + $val : $val ;
}

Related

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

Incrementing value of an array from another array

I have 2 arrays
$array1 = array(22,193,124);
$array2 = array(array('id'=>22, 'count'=> 1), array('id'=>124, 'count'=>2));
Now I need to search in $array2 for id from $array1 and if found to increment the count value and also add to the array the one's which are not found with a count as 1 so my resulting array would be
$arr = array(array('id'=>22, 'count'=> 2), array('id'=>124, 'count'=>3), array('id'=>193, 'count'=>1));
any help would be appreciated
The current code which I tried is
if($array2){
foreach($array1 as $array){
if(in_array($array, array_column($array2, 'id'))){
$wa_array['count'] += 1;
} else {
$wa_array['id'] = $array;
$wa_array['count'] = 1;
}
}
} else {
foreach($array1 as $array){
$wa_array['id'] = $array;
$wa_array['count'] = 1;
}
}
This may be something you are looking for -
$array1 = array(22,193,124);
$array2 = array(array('id'=>22, 'count'=> 1), array('id'=>124, 'count'=>2));
foreach($array1 as $key=>$digit)
{
$keyFound = array_search($digit, array_column($array2, 'id'));
if($keyFound === false)
{
array_push($array2, ['id'=>$digit, 'count'=>1]);
}
else
{
$array2[$keyFound]['count']++;
}
}
print_r($array2);
The question is not so clear, so I will go with my understanding : You need to check if values inside the first array are in the second array. If yes, increment the count value of that second array, if not, create that element with the value of 1.
This code is not tested, hope this can help find the good solution.
foreach($array1 as $value){
searchForId($value,$array2);
}
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['id'] === $id) {
$val['count'] += 1;
}else{
array_push(array('id'=>$id,'count'=>1))
}
}
return null;
}
you should loop through $array2, not $array1. Finding the value in array_column($array2, 'id') doesn't tell you the index of the array element to increment.
foreach ($array2 as &$item) {
if (in_array($item['id'], $array1)) {
$item['count']++;
}
}
Note that you have to use &$item to make this a reference to the original array element, so that modifying it will update $array2. Otherwise, $item would be a copy of the array element.
If $array1 is large, it would be better to convert it to an associative array so you can test membership more efficiently.
$array1_assoc = array_flip($array1);
Then the test in the loop becomes:
if (isset($array1_assoc[$item['id']]) {
Check this one. NOTE: But this has O(n^2) complexity.
$array1 = [22,193,124];
$array2 = [['id'=>22, 'count'=> 1], ['id'=>124, 'count'=>2]];
foreach ($array1 as $value) {
$isFound = false;
foreach ($array2 as &$item) {
if ($value == $item['id']) {
$item['count']++;
$isFound = true;
continue;
}
}
if ($isFound == false) {
$array2 [] = ['id'=>$value, 'count'=> 1];
}
}
var_dump($array2);

PHP how get new array from two arrays?

I have w1[6][9]
for($i=0;$i<6;$i++){
for($j=0;$j<9;$j++){
$key=rand(0,8);
$w1[$i][$j]=$mas[$key];
}
}
And I have s1[6];
$s1=[1,0,1,1,1,1,1,0,1];
How can I a[0..5] , where every element is a+=w1[i][j]*s[j] ?
For example: a1=0.1*1+0.2*0+0.3*1+ ...+0.5*1+0.4*0+0.2*1
iterate the array to do the multiply like this:
$o = [];
foreach($w1 as $arr)
{
$sum = 0;
foreach($arr as $k => $v)
{
$sum += $v * $s1[$k];
}
$o[] = $sum;
}
dd($o);
Take a look at this php function: http://php.net/manual/de/function.array-merge.php
It merges arrays in to one array.

Comparing Multi and single dimensional arrays in php

I am new to php just playing with some array.
I Want to get following things from the array which are of different dimensional
The following is the Multidimensional Array
$a = array(
array(
'productsid' => 90,
'CouponID' => 50
),
array(
'productsid' => 80,
'CouponID' => 95
),
array(
'productsid' => 80,
'CouponID' => 95
));
The following is Single dimensional array:
$b = array(80,90,95);
I want to compare only the productsid index of the array with the single dimensional array and wants to fetch the data which is equal to it.
I Have tried the following loop to print but it only gives the values of the productsid only but I want that full array. But only by comparing the Productid with the second array.
for ($i = 0; $i < 3; $i++) {
foreach ($a[$i] as $key => $value) {
foreach ($b as $c) {
if ($value == $c) {
echo $value .'<br>';
}
}
} }
Looks like you're looking for in_array():
$result = array();
foreach($a as $item)
if(in_array($item['productsid'], $b))
$result []= $item;
or, in a more concise (but less readable IMO) way:
$result = array_filter($a, function($item) use($b) {
return in_array($item['productsid'], $b);
});
For your test data it's doesn't matter much, but if your arrays are big and/or this loop is going to run many times, you can achieve better performance by converting the lookup array into a hash table and using O(1) key lookup instead of linear array search:
$bs = array_flip($b);
$result = array_filter($a, function($item) use($bs) {
return isset($bs[$item['productsid']]);
});
$b = array(80,90,95);
$c = array();
foreach($a as $val) {
if(in_array($val['productsid'],$b)) {
$c[] = $val;
}
}
echo "<pre>";
print_r($c);
Try this:
foreach($a as $ar) {
if (in_array($ar['productsid'], $b))
print_r($ar);
}

Sorting arrays: second last

ksort ($votes);
foreach ($votes as $total => $contestant){
$ordervotes[]= $contestant;
}
echo "<li> And the winner is: {$ordervotes[4]}</li>";
echo "<li> And the loser is: {$ordervotes[0]}</li>";
echo "<li> {$ordervotes[1]} came second last</li>";
This works fine when none of the '$total's are the same, if they are the same i get an error code. I realise I could use the 'max/min' to get the first and last elements of the array, but how do i go about finding the second last?
Thank you
Joe
Why don't you try:
echo $votes[count($votes)-2];
You also don't need to populate another array with the same values - you can keep them in $votes. You might also want to look into sorting your array by value instead of by key (which I assume you're trying to do).
If you're expecting duplicate keys, you need to remodel the way you're storing your data. Consider using a multidimensional array:
$votes = array(
array('name'=>'John','vote'=>10),
array('name'=>'James','vote'=>11),
array('name'=>'Jimmy','vote'=>13),
);
You will be able to sort this array using this function and code:
// This function will sort your array
function aasort (&$array, $key) {
$sorter=array();
$ret=array();
reset($array);
foreach ($array as $ii => $va) {
$sorter[$ii]=$va[$key];
}
asort($sorter);
foreach ($sorter as $ii => $va) {
$ret[$ii]=$array[$ii];
}
$array=$ret;
}
// Sort the array by the 'vote' key
aasort($votes,"vote");
// Echo out the name of the second-last person
echo $votes[count($votes)-2]['name'];
Use this:
function secondMax($arr) {
$max = $second = 0;
$maxKey = $secondKey = null;
foreach($arr as $key => $value) {
if($value > $max) {
$second = $max;
$secondKey = $maxKey;
$max = $value;
$maxKey = $key;
} elseif($value > $secondMax) {
$second = $value;
$secondKey = $key;
}
}
return array($secondKey, $second);
}
Usage:
$second = secondMax($votes);
You can retrieve it by using the function count:
$ordervotes[ (count($ordervotes)-2) ]
// the array starts with index 0, so (count($ordervotes)-1) is the last element
I don't understand what is in your $votes variable ... How could you have multiple contestants with the same votes (and so, with the same key).
I think there is a mistake here.
You $votes should be like this :
$votes = array(
'contestant 1' => 8,
'contestant 2' => 12,
'contestant 3' => 3
);
Then order the array : sort($votes)
Finaly, get the second last : $votes[count($votes) - 2];

Categories