1

I have a multidimensional array in the following format:

$array = array (
  0 => 
    array (
      'date' => '2013-03-25',
      'name' => 'Bob',
      'time' => '11'
    ),
  1 => 
    array (
      'date' => '2013-03-25',
      'name' => 'Brian',
      'time' => '13'
    ),
  2 => 
    array (
      'date' => '2013-03-26',
      'name' => 'Jack',
      'time' => '14'
    ),
  3 => 
    array (
      'date' => '2013-03-26',
      'name' => 'Bob',
      'time' => '14'
    )
);

I am trying to get the names and corresponding times for each date. I have got the names using the following method:

$array2 = array();
    foreach($array as $item) {
    $array2[$item['date']][] = $item['name'];
    }

and then using:

foreach($array2[$date] as $name)

to run a query on the names returned. But I am not sure how to get the corresponding 'time' key for each 'name' key in the second foreach loop.

3 Answers 3

2

Why you don't want to store both name and time for each date key?

$array2 = array();
foreach ($array as $item) {
  $array2[$item['date']] []= array($item['time'], $item['name']);
}

You can reach name and time with this code:

foreach ($array2 as $row) {
  $name = $row[0];
  $time = $row[1];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, yes, that's the way to do it. Thanks.
1

You can try

$list = array();
foreach ( $array as $k => $item ) {
    $list[$item['date']][] = array(
            $item['name'],
            $item['time']
    );
}

foreach ( $list as $date => $data ) {
    echo $date, PHP_EOL;
    foreach ( $data as $var ) {
        list($name, $time) = $var;
        echo $name, " ", $time, PHP_EOL;
    }
    echo PHP_EOL;
}

Output

2013-03-25
Bob 11
Brian 13

2013-03-26
Jack 14
Bob 14

Comments

0

try the following:

foreach($array as $item) {
   $array2[$item['date'][] = array('name' => $item['name'], 'time' => $item['time']);
}

foreach($array2[$date] as $name) {
   echo $name['name'] . ' => ' . $name['time'] . "\n";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.