iamjonesy
iamjonesy

Reputation: 25122

PHP: Accessing array variables

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

Upvotes: 1

Views: 2035

Answers (5)

fredley
fredley

Reputation: 33871

foreach ($array as $key => $value){
  echo $value['t']['tag'] . " x " . $value[0]['NumOccurrances'];
}

Upvotes: 3

Jason McCreary
Jason McCreary

Reputation: 72961

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.

Upvotes: 1

Galen
Galen

Reputation: 30170

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

Upvotes: 1

vassilis
vassilis

Reputation: 1395

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.

Upvotes: 1

RobertPitt
RobertPitt

Reputation: 57258

something like

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

Would work.

Upvotes: 4

Related Questions