dongqun9403 2013-12-14 22:17
浏览 35
已采纳

从条件中删除关联数组中的特定键

I ran into a coding situation where i'd prefer to keep a certain condition as compact as possible:

// $data and $control are arrays
if($data==$control || ($someBool && $data==$control))
    return $c;

Of course this condition makes no sense that way. My goal is to remove a key from $control in the last part of my condition, before comparing it against $data.

Of course it could be done like this:

function chopByKey(array $arr, $key){
    if(!isset($arr[$key]))
        return $arr;
    unset($arr[$key]);
    return $arr;
}

And rewrite the condition:

if($data==$control || ($someBool && $data==chopByKey($control, 'someKey') ))
    return $c;

Please note

I am looking for a solution that i can use within my condition, not any solution that requires any additional step ahead of the condition or the definition of a custom function, be it anonymous or not.

My question is

Is there any more elegant way to do this, without defining a new custom function?

If yes, how?

  • 写回答

4条回答 默认 最新

  • douxian8883 2013-12-14 22:43
    关注

    I came up with the following line:

    $control = array('hello' => 'world', 'foo' => 'bar');
    $data = array('hello' => 'world');
    $someBool = true;
    
    if ($data == $control || $someBool && $data == array_diff_key($control, array('foo' => 0))) {
    

    Side effect is that $control is not modified by the condition.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗