Checking if array value exists in a PHP multidimensional array

后端 未结 3 342
天命终不由人
天命终不由人 2021-01-15 03:09

I have the following multidimensional array:

Array ( [0] => Array 
         ( [id] => 1 
           [name] => Jonah 
           [points] => 27 )
         


        
3条回答
  •  一生所求
    2021-01-15 03:42

    What about looping over your array, checking for each item if it's id is the one you're looking for ?

    $found = false;
    foreach ($your_array as $key => $data) {
        if ($data['id'] == $the_id_youre_lloking_for) {
            // The item has been found => add the new points to the existing ones
            $data['points'] += $the_number_of_points;
            $found = true;
            break; // no need to loop anymore, as we have found the item => exit the loop
        }
    }
    
    if ($found === false) {
        // The id you were looking for has not been found, 
        // which means the corresponding item is not already present in your array
        // => Add a new item to the array
    }
    

提交回复
热议问题