1

I have a PHP array of objects, say with two properties a and b. So for example I can do

$arr['a1']->a = $z;
$x = $arr['a1']->b;

The array is currently using the value of each object's a property as the array key, e.g.

$arr['a1']->a == 'a1'

This is so I can quickly look up the object by that property. I now need to quickly look up by b, and so want to switch the keys from being set to property a to being set to b (both are unique).

Is there an easy way to do this? In-place or into another array are both fine.

1 Answer 1

3
foreach($arr as $key => $object)
{
    $arr2[$object->b] = $object;
}

This will create a new array that points to the same objects.

If you want them in one array, you can do as Joost suggested in the comments ($arr[$object->b] = $object; in the loop instead). However, that will only work if there are no duplicate keys between the two sets.

Sign up to request clarification or add additional context in comments.

6 Comments

Or even point to the same object with both keys ->a and ->b, assuming they are of different types or ranges..
@Joost, would that be as simple as doing $arr2[$object->b] = &$object; instead?
I actually ment $arr[$object->b] = $object rather than $arr2.
Ah I see, yes that would work provided the two properties combined are 100% unique, otherwise there may be some problems with an element in b over lapping an element in a.
Exactly. One would have to make sure they're of different types, or at least not in the same range.
|

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.