未设置内部eval不起作用


unset inside eval not working

我正试图从基于字符串的数组中删除一个项;

  public function delete($path){   
    // a key path given
    if(strpos($path, '.') !== false){
      $parts = explode('.', $path);
      $first_key = array_shift($parts);
      $data = $this->get($path);
      // first key doesn't exist
      if($data === false)
        return false;
      $parts = implode('"]["', $parts);
      if(eval('if(isset($data["'.$parts.'"])){ unset($data["'.$parts.'"]); return true; } return false;'))
        return $this->set($first_key, $data);
    }
    // a single key given
    if(isset($this->data[$path]){
      unset($this->data[$path]);
      return true;
    }
    return false;  
  }

而且它只适用于单键。显然,由于某种原因,eval没有修改$data

delete('test')有效,但delete('test.child')不。。。

我不明白为什么这里需要eval()。请参阅以下内容来替换您的eval()构造:

<?php
function removeFromArray(&$array, $path)
{
    if (!is_array($path)) {
        $path = explode('.', trim($path, '.'));
    }
    $current = &$array;
    while ($path) {
        $key = array_shift($path);
        // isset() would fail on `$array[$key] === null`
        if (!array_key_exists($key, $current)) {
            // abort if the array element does not exist
            return false;
        }
        if (!$path) {
            // reached the last element
            unset($current[$key]);
            return true;
        }
        if (!is_array($current[$key])) {
            // can't go deeper, so abort
            return false;
        }
        // continue with next deeper element
        $current = &$current[$key];
    }
    return false;
}
$data = array(
    'a' => 1,
    'b' => array(
        'c' => 2,
        'd' => 3,
        'e' => array(
            'f' => 4,
        ),
    ),
);
var_dump(
    removeFromArray($data, 'b.e.f'),
    $data,
    removeFromArray($data, 'b.c'),
    $data
);
function unset_multiple($arr = [], $keys = [], $limitKeys = 30){
    if($keys && count($keys) <= $limitKeys && is_array($arr) && count($arr) > 0){
        foreach($keys as $key){
      $keys[$key] = null;
        }
        return array_diff_key($arr, $keys);
    } else{
    throw new Exception("Input array is invalid format or number of keys to remove too large");
    }
}

示例名为:

$arr = array("name" => "Vuong", "age" => 20, "address" => "Saigon");
$res = unset_multiple($arr, ["name", "age"]);
//Result: ["address" => "Saigon"]

确保$keys param在$arr param中具有所有可用键(仅二维数组)。需要记住的是,此函数是快速删除数组中多个元素的助手,而不是在所有情况下都返回绝对准确的结果。