在PHP中从数组中删除切片

时间:2015-02-06 13:23:11

标签: php arrays slice

我有一个PHP数组,我想用以下规则删除元素片段:当一个元素有visible=0时,我想删除元素和后面的elements,无论是否它们是否可见。

在此示例中,我想删除twothreefoursixseven

$categories = array(
              array('id'=>'one','visible'=>1,'elements'=>2),
              array('id'=>'two','visible'=>0,'elements'=>2),
              array('id'=>'three','visible'=>0,'elements'=>1),
              array('id'=>'four','visible'=>1,'elements'=>3),
              array('id'=>'five','visible'=>1,'elements'=>2),
              array('id'=>'six','visible'=>0,'elements'=>1),
              array('id'=>'seven','visible'=>1,'elements'=>3),
              array('id'=>'eight','visible'=>1,'elements'=>2)
              );

我已尝试过以下代码段

foreach($categories as $i=>$data)
{
    if($data['visible']==0)
    {
        array_splice($categories, $i, $data['elements']);
    }
}

这是切片后的预期结果和实际结果

  • 预期:onefiveeight
  • 实际:onefourfiveseveneight

我错过了什么?

3 个答案:

答案 0 :(得分:2)

使用简单的$categories循环运行for(),将可见项目复制到新列表($cat),跳过不可见的项目以及跟随它们的指定项目数量:

// Generate the filtered list here
$cat = array();

$count = count($categories);
for ($i = 0; $i < $count; $i ++) {
    $data = $categories[$i];
    if ($data['visible']) {
       // Copy visible item
       $cat[] = $data;
    } else {
       // Do not copy and skip the specified number of extra items
       $i += $data['elements'];
    }
}

echo("Expected: one, five, eight\n");
echo('Actual  : '.implode(', ', array_column($cat, 'id'))."\n");

更新

如果您使用array_splice()删除正确数量的项目,您的解决方案也会有效:它们是1 + $data['elements']; 1是索引$i和下一个$data['elements']项目的项目。

foreach($categories as $i=>$data)
{
    if($data['visible']==0)
    {
        array_splice($categories, $i, 1 + $data['elements']);
    }
}

答案 1 :(得分:1)

非常简单:

$length  = count($categories);
$results = array();

for ($i = 0; $i < $length; $i++) {
    # just skip!
    if ($categories[ $i ]['visible'] == 0) {
        $i = ( $i + $categories[ $i ]['elements'] );        
    } else {
        array_push($results, $categories[$i]);
    }   
}

答案 2 :(得分:0)

使用array_column(&gt; php5.5.0)和array_filter的其他几种选择:

foreach (array_column($categories, 'visible') as $k => $v) {
    if (!$v) {
        $categories[$k] = $categories[$k++] = null;
    }
}

$result = array_filter($categories);
var_dump($result);

array_walk

array_walk(array_column($categories, 'visible'), function ($v, $k) use (&$categories) {
    if (!$v) {
        $categories[$k] = $categories[$k++] = null;
    }
});

$result = array_filter($categories);
var_dump($result);