recursiveRemoval - PHP Online

Form of PHP Sandbox

Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML, but do not forget to add the tag <?php in the places where the PHP script should be executed.



Your result can be seen below.

Result of php executing





Full code of recursiveRemoval.php

  1. <?php
  2.  
  3. $hits = [
  4.     '_source'  => [
  5.         'account' => [
  6.             'id'         => 123,
  7.             'first_name' => 'Foo',
  8.             'last_name'  => 'Bar',
  9.             'mail'       => 'for@bar',
  10.             'name'       => 'Foo Bar',
  11.         ],
  12.     ],
  13.     '_source2' => [
  14.         'account2' => [
  15.             'id'         => 456,
  16.             'first_name' => 'Foo2',
  17.             'last_name'  => 'Bar2',
  18.             'mail'       => 'for@bar2',
  19.             'name'       => 'Foo Bar2',
  20.         ],
  21.     ],
  22.     'parent' => [
  23.         'authors' => [
  24.             [
  25.                 'id'         => 777,
  26.                 'first_name' => 'Foo',
  27.                 'last_name'  => 'Bar',
  28.                 'mail'       => 'for@bar',
  29.                 'name'       => 'Foo Bar',
  30.             ],
  31.         ],
  32.  
  33.     ],
  34.     'fields'   => [
  35.         'in_array_strict_mode' => [
  36.             0 => 21,
  37.         ],
  38.     ],
  39. ];
  40.  
  41. $accountFieldsToRemove = [
  42.     'first_name',
  43.     'last_name',
  44.     'mail',
  45.     'name',
  46. ];
  47.  
  48. recursiveRemoval($hits, $accountFieldsToRemove);
  49. print_r($hits);
  50.  
  51. function recursiveRemoval(array &$hits, array $accountFieldsToRemove)
  52. {
  53.     foreach ($hits as $key => &$hitElement) {
  54.         if (is_array($hitElement)) {
  55.             recursiveRemoval($hitElement, $accountFieldsToRemove);
  56.         } else {
  57.             if (in_array($key, $accountFieldsToRemove, true)) {
  58.                 unset($hits[$key]);
  59.             }
  60.         }
  61.     }
  62. }
File Description
  • recursiveRemoval
  • PHP Code
  • 29 Sep-2022
  • 1.39 Kb
You can Share it: