PHP how get new array from two arrays? - php

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.

Related

Add the same elements of an array in a recursive way

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

Sum values received from foreach loop php

I want to sum the values in my custom function, where the argument/parameter received is a variable from the foreach loop in another file.
Below is the code:
// $value is the looped variable from another function
function custom_function($value) {
// simple logic
$var = [];
$var += $value;
print_r($var);
// using array logic
$array = [];
$array[] = $value;
print_r($array);
}
The issue is, using any of the print_r I'm getting the output as:
Array
(
[0] => 100
)
Array
(
[0] => 200
)
What I need is 300, i.e. the sum of 100 + 200 the reason I suspect is the $value is the looped variable.
You can use a static variable to maintain the sum between function calls:
function custom_function($value) {
static $var = 0;
$var += $value;
echo "$var\n";
}
custom_function(100);
custom_function(200);
Output:
100
300
Demo on 3v4l.org
$a = array('10','20','30');
$result = array();
$temp = 0;
foreach($a as $v)
{
$temp = $v+$temp;
array_push($result,$temp);
}
echo end($result);
echo '<br>';
print_r($result);
I am thinking $a is an array of which values are passed. Try doing this if you dont want to change much of the logic just create 2 temporary variables
You can use array_sum to calculate the sum of array values
function custom_function($value) {
// simple logic
$var = [];
$var += $value;
print_r($var);
print_r(array_sum($var));
}
$array = array('100','200');
$res= array(); //declare a new array
foreach($array as $val)
{
array_push($res,$val); // push each element to newly created array
}
custom_function($res); //call custom function to calculate the sum of array elements

PHP Transform mixed sequential and associative array to associative array

I would like to build $goal array from $initial only. Any ideas? Thank you
Edit : the question could be how to differentiate associative parts from sequential ones.
$intial=[
"one",
"two"=>"myTwo",
"three",
"four"=>"myFour"
];
$goal=[
"one"=>null,
"two"=>"myTwo",
"three"=>null,
"four"=>"myFour"
];
The 'sequential' parts will have numeric keys, so if your 'associative' keys will always be strings, you could use that to differentiate:
$goal = [];
foreach ($initial as $key => $value) {
if (is_numeric($key)) {
$goal[$value] = null;
} else {
$goal[$key] = $value;
}
}
$goal = [];
foreach($initial as $key => $val){
if(isset($val){
$goal[$key] = $val;
}else{
$goal[$key] = $key;
}
}

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