在eval内部没有工作

时间:2012-02-05 12:13:43

标签: php arrays string

我正在尝试根据字符串从数组中删除项目;

  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')没有...

2 个答案:

答案 0 :(得分:1)

我不明白你为什么需要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
);

答案 1 :(得分:1)

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中的所有可用键(仅限二维数组)。需要记住这个函数是帮助快速删除数组的多个元素,而不是函数返回所有情况下的绝对准确结果。