1

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

Colin Hebert
93.5k16 gold badges164 silver badges154 bronze badges
asked Sep 19, 2010 at 17:17

5 Answers 5

4

something like

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

Would work.

answered Sep 19, 2010 at 17:20
Sign up to request clarification or add additional context in comments.

Comments

3
foreach ($array as $key => $value){
 echo $value['t']['tag'] . " x " . $value[0]['NumOccurrances'];
}
answered Sep 19, 2010 at 17:20

1 Comment

-1 is this PHP? Should be foreach ($array as $value) { ... }.
1

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.

answered Sep 19, 2010 at 17:20

1 Comment

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'));
1
foreach( $a as $item ) {
 echo $item['t']['tag'] . 'x' . $item[0]['NumOccurrances'] . '<br>';
}
answered Sep 19, 2010 at 17:20

Comments

1

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.

answered Sep 19, 2010 at 17:24

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.