donglinli2027 2009-11-25 13:33
浏览 5
已采纳

如何在php而不是默认哈希中使用密钥重复创建数据结构?

I want to create wrapper class, which will enable keys duplicates while default hash does not allow it. Class should use member overloading mechanism introduced in php5, so it would imitate all the behavior standard hash has. For example, I want to have smth like

$var => obj( :values_arr -> array(
      obj(:key -> 'mykey', :value -> 'val1'), 
      obj(:key -> 'mykey', :value -> 'val2')
    )
)

If I want to get $var['mykey'], it should return array('val1', 'val2'), but if I want to extend obj with new 'mykey' => 'value' pair, I would call

$val['mykey'][] = 'value'

Main idea is that behavior of the hash was preserved and after attempt to assign value to using existing key, it wouldn't be overwritten, but appended to the list.

How would you imitate other data structures in php5 (before 5.3)? Are there any known solutions or examples you want to share?

  • 写回答

2条回答 默认 最新

  • dongmi5015 2009-11-25 13:50
    关注

    like this

    class MultiMap
    {
        protected $map = array();
    
        function __set($key, $val) {
            if(!isset($this->map[$key]))  
               return $this->map[$key] = $val;
            if(!is_array($this->map[$key]))
               $this->map[$key] = array($this->map[$key]);
            $this->map[$key][] = $val;
        }
        function __get($key) {
           return $this->map[$key];
        }
    }
    
    $m = new MultiMap;
    $m->foo = 1;
    $m->foo = 2;
    $m->bar = 'zzz';
    print_r($m->foo);
    print_r($m->bar);
    

    but the whole idea looks a bit odd to me. Can you explain why you need this?

    it's not clear for me why you need operators as keys in your AST perhaps a structure like this would be more convenient

       ('op' => 'AND', 'args' => [
            (op => AND, args => [
                (op  => atom, value => word1),
                (op  => atom, value => word2),
            ]),
            (op => AND, args => [
                (op  => atom, value => word3),
                (op  => atom, value => word4),
            ])
        ])
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!
  • ¥15 怎样解决power bi 中设置管理聚合,详细信息表和详细信息列显示灰色,而不能选择相应的内容呢?
  • ¥15 QTOF MSE数据分析
  • ¥15 平板录音机录音问题解决
  • ¥15 请问维特智能的安卓APP在手机上存储传感器数据后,如何找到它的存储路径?