-3

I'm working on a small idea using PHP with Laravel and i would like to delete the endpoint key. if exists.

array:2 [▼
  "multiple" => array:2 [▼
    0 => array:5 [▼
      "label" => "EDIT"
      "key" => "edit"
      "method" => "GET"
      "icon" => "EDITICON"
      "endpoint" => "settings.attributes.edit"
    ]
    1 => array:5 [▼
      "label" => "Delete"
      "key" => "edit"
      "method" => "DELETE"
      "icon" => "DELETEICON"
      "endpoint" => "settings.attributes.delete"
    ]
  ]
  "bulk" => array:1 [▼
    0 => array:4 [▼
      "label" => "DELETE"
      "method" => "PUT"
      "type" => "DELETE"
      "endpoint" => "settings.attributes.delete"
    ]
  ]
]
AiTech
  • 75
  • 6

3 Answers3

0
public function clean(&$array, $unwanted_key) {
    unset($array[$unwanted_key]);
    foreach ($array as &$value) {
        if (is_array($value)) {
            $this->clean($value, $unwanted_key);
        }
    }
}

try this one

Maik Lowrey
  • 10,972
  • 4
  • 14
  • 43
Ruth Davis
  • 112
  • 8
0

You can use PHP's native function unset() to delete an element from array.

unset($arr["endpoint"]);
Asad Hayat
  • 368
  • 1
  • 19
0

You can make it with recursion. But in this case you can make a small but nice workaround. only for learning effects ;-) @Ruth Davis answer is good but she is not very flexible. Therefore recursion. But not everyone likes recursion.

$array = [
    'multiple' => [
        [
            "label" => "EDIT",
            "key" => "edit",
            "method" => "GET",
            "icon" => "EDITICON",
            "endpoint" => "settings.attributes.edit",
        ],
        [
            "label" => "Delete",
            "key" => "edit",
            "method" => "DELETE",
            "icon" => "DELETEICON",
            "endpoint" => "settings.attributes.delete",
        ]
    ],
];

$pattern = '/(,\"endpoint\"\:\".*?\")/i';
$result = preg_replace($pattern, '', json_encode($array));
$clearedArray = json_decode($result, true);
print_r($clearedArray);
Maik Lowrey
  • 10,972
  • 4
  • 14
  • 43