0

I am generating array like this

Array ( 
[0] => Array ( [s_email] => amelia@example.com [s_inbox] => 0 [s_spam] => 10 ) 
[1] => Array ( [s_email] => claire@example.com [s_inbox] => 0 [s_spam] => 10 ) 
)

Later in my script I need to update value of s_inbox and s_spam something like below

[s_email] => amelia@example.com [s_inbox] => 1000

[s_email] => claire@example.com [s_inbox] => 2000

I have searched some answers but most of are key based but instead here I want modify it by emails. Let me know if anyone here can help me for the same.

Thanks!

ADyson
  • 57,178
  • 14
  • 51
  • 63
Sunil Jain
  • 45
  • 8
  • For each one you need to change, search by the email property value to get the index, then you know which index to update within. https://stackoverflow.com/questions/6661530/php-multidimensional-array-search-by-value should get you started. – ADyson Jul 16 '23 at 17:08
  • You didn't tell us whether the email addresses in the generated array are unique. They probably are, but we cannot assume that. If they are you don't have to (explicitly) search for the correct key for each row you want to update. – KIKO Software Jul 16 '23 at 17:13

1 Answers1

1

This can be achived with array_walk method, it applies a callback for each item in the array.

Given the array:

$a = [ [ 's_email' => 'amelia@example.com', 's_inbox' => 0 ,'s_spam' => 10 ],
       [ 's_email' => 'claire@example.com','s_inbox' => 0, 's_spam' => 10 ]];

We want to apply the callback update_s_inbox for each item:

function update_s_inbox(&$item, $key,  $data)
{
    
    $email = $data[0];
    $s_inbox = $data[1];
    if ($item['s_email']==$email) {
        $item['s_inbox']=$s_inbox;  
    }
    
}


$email = 'amelia@example.com';
$s_inbox = 1000;
array_walk($a, 'update_s_inbox', [$email, $s_inbox]);

Probably the optimal approach if the emails can repeat. If the emails are unique, it is probably better to put the email as array key.

Grigory Ilizirov
  • 1,030
  • 1
  • 8
  • 26