views:

60

answers:

5

Can someone help me access this array please I'm having trouble with indexes.

array(10) {
    [0]=>array(2) {
        ["t"]=>array(1) {
            ["tag"]=>string(3) "php"
        }
        [0]=>array(1) {
            ["NumOccurrances"]=>string(1) "2"
        }
    }
    [1]=>array(2) {
        ["t"]=>array(1) {
            ["tag"]=>string(6) "Tomcat"
        }
        [0]=>array(1) {
            ["NumOccurrances"]=>string(1) "1"
        }
    }
}

I want to use it in a foreach loop displaying like "PHP x 2" but am having trouble with the indexes

Thanks

Jonesy

+3  A: 
foreach ($array as $key => $value){
  echo $value['t']['tag'] . " x " . $value[0]['NumOccurrances'];
}
fredley
-1 is this PHP? Should be `foreach ($array as $value) { ... }`.
nikic
Amended, sorry for the confusion, too much Python recently...
fredley
+3  A: 

something like

foreach($array as $entity)
{
    echo $entity['t']['tag'] . ' x ' . $entity[0]['NumOccurrances']; 
}

Would work.

RobertPitt
+1  A: 

Does this do?

foreach ($tags as $t) {
    echo $t['t']['tag'].' x '.$t[0]['NumOccurrances'].'<br />';
}

The structure seems a bit weird. If this does not help, please provide the rest of array.

vassilis
thanks! yeah you are right it's a strange structure but it's coming out of a cakePHP method that looks like this: $this->set('tags', $this->Project->query('SELECT t.tag, COUNT(*) AS NumOccurrances FROM projects_tags pt INNER JOIN tags t ON t.id = pt.tag_id GROUP BY t.tag ORDER BY 2 DESC'));
iamjonesy
+1  A: 
foreach( $a as $item ) {
    echo $item['t']['tag'] . 'x' . $item[0]['NumOccurrances'] . '<br>';
}
Galen
+1  A: 

I wouldn't use a foreach loop here. foreach creates a copy of the array and therefore is not as efficient as a for loop. Since your first dimension is numerically indexed, I would do the following:

$count = count($array);
for ($i = 0; $i < $count; ++$i){
  echo $array[$i]['t']['tag'] . " x " . $array[$i][0]['NumOccurrances'];
}

I agree with vassilis that the array structure is odd.

Jason McCreary