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.     '_source'  => [
  23.         'parent' => [
  24.             'authors' => [
  25.                 [
  26.                     'id'         => 777,
  27.                     'first_name' => 'Foo',
  28.                     'last_name'  => 'Bar',
  29.                     'mail'       => 'for@bar',
  30.                     'name'       => 'Foo Bar',
  31.                 ],
  32.             ],
  33.  
  34.         ],
  35.     ],
  36.     'fields'   => [
  37.         'in_array_strict_mode' => [
  38.             0 => 21,
  39.         ],
  40.     ],
  41. ];
  42.  
  43. $accountFieldsToRemove = [
  44.     'first_name',
  45.     'last_name',
  46.     'mail',
  47.     'name',
  48. ];
  49.  
  50. recursiveRemoval($hits, $accountFieldsToRemove);
  51. print_r($hits);
  52.  
  53. function recursiveRemoval(array &$hits, array $accountFieldsToRemove)
  54. {
  55.     foreach ($hits as $key => &$hitElement) {
  56.         if (is_array($hitElement)) {
  57.             recursiveRemoval($hitElement, $accountFieldsToRemove);
  58.         } else {
  59.             if (in_array($key, $accountFieldsToRemove, true)) {
  60.                 unset($hits[$key]);
  61.             }
  62.         }
  63.     }
  64. }
File Description
  • recursiveRemoval
  • PHP Code
  • 29 Sep-2022
  • 1.46 Kb
You can Share it: