0

My array looks like here:

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

I try to create function that returns the string of the item by taking the number of the item as input. As example, my function readItem($number) would return "Get car cleaned" if I give the input $number = 3. There is highpriority and lowpriority nodes but more will be added, like mediumpriority, toppriority and so forth... I am thinking removing the parents in the array (the highpriority and lowpriority node) I can use $array[$number] to read the item string, correct?

With array_shift(), only children of highpriority remained. How can I make it go through every parent? I found here some code but it relies on knowing the parent by name: remove "wrapping" array (remove parent, keep children). If it can help, the data to my array is read from CSV using code from nickb in my previous question: Grouping CSV input by columns.

I am sure the solution is trivial, but is there other way beside a foreach loop and adding children manually to a new array? Thank you

Community
  • 1
  • 1

2 Answers2

0

With your priorities having names, the only way to know their proper ordering is to enumerate them somewhere.

// 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;
  }
}
Gary G
  • 5,692
  • 2
  • 27
  • 18
0

There you go:

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

?>
daschl
  • 1,124
  • 6
  • 11