删除阵列中的父母,同时保持儿童结构完整

时间:2012-08-02 09:56:34

标签: php arrays

我的数组如下所示:

array(2) {
  ["highpriority"]=>
  array(2) {
    [0]=> // 1st item
    array(2) {
      [0]=>
      string(14) "Do the laundry"
      [1]=>
      string(6) "Sunday"
    }
    [1]=> // 2nd item
    array(2) {
      [0]=>
      string(19) "Study for math exam"
      [1]=>
      string(6) "Monday"
    }
  }
  ["lowpriority"]=>
  array(2) {
    [0]=> // 3rd item
    array(2) {
      [0]=>
      string(15) "Get car cleaned"
      [1]=>
      string(9) "Next week"
    }
    [1]=>
    array(2) { // 4th item
      [0]=>
      string(33) "Buy The Amazing Spider-Man on DVD"
      [1]=>
      string(5) "Later"
    }
  }
}

我尝试通过将项目的编号作为输入来创建返回项目字符串的函数。例如,如果我给输入$ number = 3,我的函数readItem($ number)将返回“get car cleaning”。有高优先级和低优先级节点,但会增加更多,如mediumpriority,toppriority等等......我我在考虑删除数组中的父项(highpriority和lowpriority节点)我可以使用$ array [$ number]来读取项目字符串,对吗?

使用array_shift(),只有高优先级的孩子仍然存在。我怎样才能让它通过每个家长?我在这里找到了一些代码,但它依赖于通过名称知道父代:remove "wrapping" array (remove parent, keep children)。如果它可以提供帮助,我可以使用上一个问题中的nickb代码从CSV中读取数据到我的数组:Grouping CSV input by columns

我确信这个解决方案很简单,但是在foreach循环旁边还有其他方法可以手动将子项添加到新数组中吗?谢谢

2 个答案:

答案 0 :(得分:0)

如果您的优先级有名称,那么了解其正确排序的唯一方法就是在某处枚举它们。

// Assume the data array is named $tasks.
function readItem($number) {
  $priorities = ['highpriority', 'lowpriority'];
  $total = 0;
  foreach($priorities as $priority) {
    $thiscount = count($tasks[$priority]);
    if($number <= $total + $thiscount) {
      // The item is in this priority.
      return $tasks[$priority][$number - $total - 1][0]
    }
    $total += $thiscount;
  }
}

答案 1 :(得分:0)

你去了:

<?php

$input = array(
    'high' => array(
        array('Do the laundry', 'Sunday'),
        array('Study math', 'Monday')
    ),
    'low' => array(
        array('Get car cleaned', 'Next Week')
    )
);

$output = array();
array_walk_recursive($input, function($item, $key) use (&$output) {
    $index = count($output) - $key;
    $output[$index][] = $item;
});

$readItem = function($index) use ($output) {
    return $output[$index-1];
};

var_dump($readItem(3));

?>
相关问题