0

In my web application, a user has the choice to enable and disable certain "notification preferences", their choices are added to an array for each possible category and alerts within a JSON object, this is then saved to the database, I'm trying to remove ALL mentions of a specific "channel" if it's set without having to know what to loop over and what nested items I have.

For instance, the following structure:

$channels = json_encode([
    'domains' => [
      'expiry' => ['mail', 'database', 'slack']
    ],
    'ssl' => [
      'expiry' => ['mail', 'database', 'slack']
    ],
    'monitors' => [
      'up' => ['mail', 'database', 'slack'],
      'down' => ['mail', 'database', 'slack']
    ]
]);
              

$preferences = json_decode($channels);

I'd like to somehow find all mentions of **slack"" and then simply remove that item from my arrays, it may not always be in the same position, depending on what a user enables/disables...

I was thinking of using unset or something similar?

How can I achieve this with my code?

miken32
  • 42,008
  • 16
  • 111
  • 154
Ryan H
  • 2,620
  • 4
  • 37
  • 109
  • 1
    Loop through it and do your checks. Writing to a new object will be preferable to updating the object you are looping through. – miken32 Mar 10 '21 at 19:17
  • Because I can't find the answer at https://stackoverflow.com/questions/29308898/how-do-i-extract-data-from-json-with-php and the question is already closed, here's the code you need. $categories = get_object_vars($preferences); foreach($categories as $categoryName => $settings) { $settingsNames = get_object_vars($settings); foreach($settingsNames as $settingsName => $values) { $preferences->$categoryName->$settingsName = array_filter($values, function($item) { return $item !== "slack"; }); } } – Tobias Rohde Mar 10 '21 at 19:48

0 Answers0