Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm editing someone else's code here:

foreach($list as $items) {
   // displays items names and images etc
}

and within the foreach() loop I can see the name using:

echo $items[0]->name

and looking at the contents of $items it looks like this:

Array ( [0] => stdClass Object ( [id] => 7 [name] => Bench Scales // ..etc..

But I can't seem to reference name outside the loop

$list[0]->name // doesn't work

So I'm kinda stuck at this point when trying to sort by name, Yep I've looked up usort() and am happy with the concept of sorting by name, but am unable to sort this array of objects? by name. Any help most welcome

Above the foreach() loop I tried something like this, but no luck:

function cmp($a,$b) { return strcmp($a->name, $b->name); }
usort($list,"cmp");
share|improve this question
    
$list[0]->name is not the same as $items[0]->name. Why do you think they are interchangeable? –  zerkms Dec 9 '13 at 2:47
    
Btw, in loop you're using $items[0]->name and in comparison function - $a->name. What makes you thinking that [0] is an optional element? –  zerkms Dec 9 '13 at 2:54
    
Leemo's answer's below helped me reference it, bit silly really my brain was turned off today :/ - Code included in my comment below his answer. Thanks for your help guys –  user975033 Dec 10 '13 at 9:35

2 Answers 2

up vote 3 down vote accepted

This example:

$list[0]->name; // doesn't work

Shouldnt work Remember that when you're inside a foreach, you're one level nested when you access the iterable such as $item. Therefore

Assuming that the array has numeric indicies and that The 0th value in $list is an object this would work:

$list[0][0]->name;
share|improve this answer
    
You're making an assumption that $list has numeric based and continuous indexes –  zerkms Dec 9 '13 at 2:48
    
Exactly... I should clarify in answer body –  leemo Dec 9 '13 at 2:49
    
Ah I was a bit brain dead, your right, $list[0][0]->name and $list[x][0]->name will work, so when I run $list thru a sorting bit of code: the changes are this: function cmp($a,$b) { return strcmp($a[0]->name, $b[0]->name); } usort($list,"cmp"); Thankyou so much! –  user975033 Dec 10 '13 at 9:33

To me (and I'm kind of tired right now) this doesn't look like a sort issue. $list is a collection (obviously) and when you run it through the foreach loop, each iteration is giving you a single object array to work with, which is why your first example works. $list is an array of arrays, so you need one more level of "access" to get what you want.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.