2012-08-02 20 views
0

我的阵列看起来像在这里:在阵列中取出的父母,同时保持儿童结构完整

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" 
    } 
    } 
} 

我尝试创建功能,通过采取项目作为输入的号码回到该项目的字符串。例如,我的函数readItem($ number)会返回“获取汽车清理”,如果我给出输入$ number = 3。有高优先级和低优先级节点,但会添加更多,如中间优先级,优先级等... I我正在考虑删除数组中的父项(高优先级和低优先级节点)我可以使用$ array [$ number]来读取项目字符串,对吗?

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

我相信解决方案是微不足道的,但有没有其他方式在foreach循环旁边,并手动添加孩子到一个新的数组?谢谢你

回答

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)); 

?> 
+0

这究竟是我想要的,谢谢!我接受了你的答案 – 2012-08-02 12:01:37

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; 
    } 
}