Home > OS >  how to delete endpoint key. if it exists
how to delete endpoint key. if it exists

Time:10-16

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"
    ]
  ]
]

CodePudding user response:

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

unset($arr["endpoint"]);

CodePudding user response:

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

CodePudding user response:

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);
  •  Tags:  
  • php
  • Related