PHP replace multiple values from an array to another one - php

I want to insert the values from the first array inside the second array, where the key's name is [cost]:
$newcosts
Array (
[0] => 52.68
[1] => 7414.68
[2] => 2471.56
)
$mainarray
[0] => Array (
[id] => 2
[date] => 15.12.2020
[cost] => 60.00
)
[1] => Array (
[id] => 1
[date] => 22.12.2020
[cost] => 60.00
)
[2] => Array (
[id] => 3
[date] => 24.12.2020
[cost] => 22.00
)
I tried the following:
foreach ($mainarray as $key => $value) {
$values[] = $value['cost'];
$new_array[] = str_replace($values, $newcosts, $value);
}
for some reason, this is not showing the right data and sometime they get repeated. this is an example:
[0] => Array (
[id] => 2
[date] => 15.12.2020
[cost] => 52.68
)
[1] => Array (
[id] => 1
[date] => 22.12.2020
[cost] => 52.68
)
[2] => Array (
[id] => 3
[date] => 24.12.2020
[cost] => 2471.56
)
Hope someone could help me on that. Thank you very much!

Just use the mainarray's index to replace the $newcosts into the array.
foreach ($mainarray as $index => $subarray) {
$mainarray[$index]['cost'] = $newcosts[$index];
}
Because you will have an unused variable $subarray this way, it would be nicer to use a for loop:
for ($i = 0; $i < count($mainarray); $i++) {
$mainarray[$i]['cost'] = $newcosts[$i];
}

user foreach to get value of $newcosts and then
in loop replace value of price by id
in foreach loop you shuld replace value of $mainarray
foreach($newcosts as $itme => $value){
$mainarray [$itme ]['cost'] = $value;
}

Why are you using str_replace to replace float value ?
You can also index your array like this
for ($idx = 0; $idx <= count($mainarray); $idx++) {
$mainarray[$idx]['cost'] = $mainarray[$idx];
}
edit : same solution as above

A function-based equivalent to classic loops is to call array_walk() and modify the rows by reference. Using arrow function syntax (since PHP7.4) means you don't have to use use().
Code: (Demo)
array_walk(
$mainarray,
fn(&$row, $i) => $row['cost'] = $newcosts[$i]
);
var_export($mainarray);

Related

Combining arrays with common values

I have an array of dates that looks like this:
Array
(
[0] => '2014-01-01'
[1] => '2014-01-02'
[2] => '2014-01-03'
[3] => '2014-01-04'
[4] => '2014-01-05'
[5] => '2014-01-06'
[6] => '2014-01-07'
)
and I have another array of dates and counts that looks like this:
[All] => Array
(
[0] => Array
(
[count] => 2
[date] => 2014-01-06
)
[1] => Array
(
[count] => 1
[date] => 2014-01-03
)
[2] => Array
(
[count] => 43
[date] => 2013-12-11
)
[3] => Array
(
[count] => 103
[date] => 2013-12-10
)
[4] => Array
(
[count] => 128
[date] => 2013-12-09
)
[5] => Array
(
[count] => 75
[date] => 2013-12-08
)
[6] => Array
(
[count] => 107
[date] => 2013-12-07
)
I want to make a new associative array where all the keys are the dates from the first array above and all of the values are either the count matched up with the corresponding date or "0".
So for instance, the new array would look like this:
Array
(
[2014-01-01] => 0
[2014-01-02] => 0
[2014-01-03] => 1
[2014-01-04] => 0
[2014-01-05] => 0
[2014-01-06] => 2
[2014-01-07] => 0
)
Does that make sense? Please feel free to ask any questions you may have. Thank you!
Try this code:
$result = array();
foreach($firstArray as $f){
foreach($secondArray as $s){
if($s['date'] == $f) $result[$f] = $s['count'];
}
if(!array_key_exists($f, $result)) $result[$f] = 0;
}
$result = array();
foreach($secondArray as $s){
if(in_array($s['date'], $firstArray) {
unset($firstArray[$s['date']]);
$result[$s['date']] = $s['count'];
}
}
// if items left in first array that are not found within foreach:
if (!empty($firstArray))
$result = array_merge($result, array_fill_keys($firstArray, 0));
// sort by key so dates go ascending
ksort($result);
$new = array();
foreach($all as $row)
{
$new[$row['date']] = $row['count'];
}
array_merge ($new, $old);
Here $all is the array with the date and count indices.
$old is the exisisting array.
That's a 2-liner:
// use dates as index and set everything to 0
$result = array_fill_keys($x, 0));
// copy over existing counts
array_walk($all, function($v) use (&$result) { if (array_key_exists($v['date'], $result)) { $result[$v['date']] = $v['count'];}});

list duplicates in PHP Array

i have a new problem and my mind is burning, i have an array in php
$test = array();
Array
(
[0] => Array
(
[account] => 14319896
[value] => 725.57
[id] => 280
)
[1] => Array
(
[account] => 163157
[value] => -723.57
[id] => 283
)
[2] => Array
(
[account] => 163157
[value] => 723.57
[id] => 284
)
[3] => Array
(
[account] => 161817
[value] => -723.57
[id] => 285
)
)
i need the accounts, they are more than one in this array, in this example i need $test[1][id] and $test[2][id]
have you an idea? i have no idea more at this time.
Thanks for your help.
Use the account number as key in a new array, count each entry and then take the items with a count > 1
$dupes = array();
foreach($array as $account) {
++$dupes[$account['account']];
}
$dupes = array_filter($dupes, function($count) { return $count > 1; });
Editing to answer the comments below the question …
If you want the IDs (or keys) of the duplicates, do not store the count directly, but use another array instead.
$dupes = array();
foreach($array as $key => $account) {
if(!array_key_exists($account, $dupes))
$dupes[$account['account']] = array();
$dupes[$account['account']][] = $account['id']; // or: = $key
}
$dupes = array_filter($dupes, function($ids) { return count($ids) > 1; });
You should change your architecture to have a associative array where keys are account number organized like that :
Array
(
[14319896] => Array
(
[0]=>Array(
[value] => 725.57
[id] => 280
)
)
[163157] => Array
(
[0]=>Array(
[value] => -723.57
[id] => 283
)
[1]=>Array(
[value] => 723.57
[id] => 284
)
)
[161817] => Array
(
[0]=>Array(
[value] => -723.57
[id] => 285
)
)
)
$dupes = array();
foreach($array as $key => $account) {
$dupes[$account['account']][] = array($account['id'],$account['value']);
}
Whith that architecture you can get everything you want thanks to array_filter :
$dups = array_filter($dupes, function($account){ return count($account)>1;});

Remove item from multidimensional array php

Here is the array:
[cart] => Array
(
[ProductId] => Array
(
[0] => P121100001
[1] => P121100002
)
[SellerId] => Array
(
[0] => S12110001
[1] => S12110001
)
[SpecifyId] => Array
(
[0] => 1
[1] => 2
)
[Quantity] => Array
(
[0] => 1
[1] => 1
)
[Price] => Array
(
[0] => 12
[1] => 29
)
[TotalPrice] => 41
)
I have the ProductId and I want to remove all the other items matching P121100002's key.
Is there an easy way to do this I can't can seem to come up with one?
You can loop through the full array and use unset() to, well, "unset" the specified index:
$index = array_search($cart['ProductId'], 'P121100002');
if ($index !== false) {
foreach ($cart as $key => $arr) {
unset($cart[$key][$index]);
}
}
The slight caveat to this approach is that it may disrupt your index orders. For instance, say you have:
[ProductId] => Array (
[0] => P121100001
[1] => P121100002
[2] => P121100003
)
And you want to remove P121100002, which has a corresponding index of 1. Using unset($cart['ProductId'][1]) will cause your array's to become:
[ProductId] => Array (
[0] => P121100001
[2] => P121100003
)
This may be something to remain concerned with if you're going to use a for loop to iterate through in the future. If it is, you can use array_values() to "reset" the indexes in the unset() loop from above:
foreach ($cart as $key => $arr) {
unset($cart[$key][$index]);
$cart[$key] = array_values($cart[$key]);
}
foreach($yourArray['ProductId'] as $key => $value) {
if ($value == $productIdToRemove) {
foreach($yourArray as $deleteKey => $deleteValue) {
unset($yourArray[$deleteKey][$key]);
}
break;
}
}
Use array_key_exists along with the unset() function

PHP combine array based on value of particular element

I have an array that looks like this
Array (
[0] => Array
(
[id] => 123
[count] => 1
)
[1] => Array
(
[id] => 123
[count] => 3
)
[2] => Array
(
[id] => 513
[count] => 0
)
[3] => Array
(
[id] => 561
[count] => 1
)
[4] => Array
(
[id] => 613
[count] => 7
)
)
What I want to do is create a new array, that totals the count where the id values are the same. So for example, the new array would look like this:
Array (
[0] => Array
(
[id] => 123
[count] => 4
)
[1] => Array
(
[id] => 513
[count] => 0
)
[2] => Array
(
[id] => 561
[count] => 1
)
[3] => Array
(
[id] => 613
[count] => 7
)
)
Would anyone know a good method to do this?
Thank you!
Short and simple:
$new_array = array();
foreach($data_array as $value) {
if(array_key_exists($value['id'], $new_array)) {
$new_array[$value['id']] += $value['count'];
} else {
$new_array[$value['id']] = $value['count'];
}
}
echo print_r($new_array,true);
I made it id => value since there didn't seem to need another array for data when the id could be used as the array's key.
Any reason why you are not making an associative array of id => count
You can do it with the following function (I didn't tested the code, but it should work ):
function get_count_array($arr) {
$new_array = array();
foreach($arr as $item) {
$found = false;
//loop through all the current new items to check if we already have it
for($i = 0; $i < count($new_array); $i++) {
//do we have it?
if($new_array[$i]['id'] == $item['id']) {
$new_array[$i]['count'] += 1;
$found = true;
break;
}
}
if(!$found) {
$new_array[] = array('id' => $item['id'], 'count' => 0);
}
}
return $new_array;
}

Looping through array and totalling values

I require a bit of assistance, if someone would be kind enough to help.
I have an array with values, which I want to loop through, and if any of the 'user_id values' are the same then to total the 'max_score' value of the duplicate user id's.
Array
(
[0] => Array
(
[user_id] => 2
[max_score] => 10081
)
[1] => Array
(
[user_id] => 1
[max_score] => 8774
)
[2] => Array
(
[user_id] => 2
[max_score] => 5477
)
[3] => Array
(
[user_id] => 3
[max_score] => 5267
)
[4] => Array
(
[user_id] => 1
[max_score] => 5010
)
)
Would anyone know how to accomplish this?
Many thanks.
$totals = array();
foreach ($your_array_values as $v) {
$id = $v['user_id'];
if (isset($totals[$id])) {
$totals[$id] += $v['max_score'];
} else {
$totals[$id] = $v['max_score'];
}
}
you need a second array with the user ids as key. You can do it like this:
$scoresums = array();
foreach ($yourarray AS $user_score) {
if (!isset($scoresums[$user_score['user_id']])) $scoresums[$user_score['user_id']] = 0;
$scoresums[$user_score['user_id']] += $user_score['max_score'];
}
The third line will prevent php from throwing notices.

Categories