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

アイテム番号を入力して、アイテムの文字列を返す関数を作成してみました。たとえば、入力$ number = 3を指定すると、関数readItem($ number)は「Getcarcleaned」を返します。highpriorityノードとlowpriorityノードがありますが、mediumpriority、toppriorityなどのノードが追加されます... I配列(高優先度ノードと低優先度ノード)の親を削除することを考えています。$ array [$ number]を使用してアイテム文字列を読み取ることができますか?

array_shift()を使用すると、優先度の高い子のみが残ります。どうすればすべての親を通過させることができますか?ここでいくつかのコードを見つけましたが、名前で親を知ることに依存しています:「wrapping」配列を削除します(親を削除し、子を保持します)。それが役立つ場合は、私の配列へのデータは、私の前の質問のnickbからのコードを使用してCSVから読み取られます:列によるCSV入力のグループ化

解決策は簡単だと思いますが、foreachループのほかに、子を手動で新しい配列に追加する方法はありますか?ありがとうございました

4

2 に答える 2

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;
  }
}
于 2012-08-02T10:28:10.463 に答える
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));

?>
于 2012-08-02T10:49:27.577 に答える