4
<?php

// get unordered array of Group objects
$groups = $this->getDoctrine()->getManager()->getRepository('AcmeDemoBundle:Group');

$array = array();
// map array to $groupName => $groupObject
foreach ($groups as $group) {
    $array[$group->getName()] = $group;
}

Is there a shorter way to do that in PHP?

Note: Group names are unique, not empty strings.

I was thinking about array_walk, but I'm not sure if can replace the key somehow?

5
  • 3
    That looks pretty short to me. Commented Jan 2, 2014 at 13:54
  • Since this is a doctrine2-related question, check out DQL's index by: docs.doctrine-project.org/en/2.1/reference/… Commented Jan 2, 2014 at 13:56
  • 2
    You can do nasty things with combining the array with a mapped array, but that won't be faster, and be more obscure. Your code example is fine, well readable for any other developer, and performs as well or even better then one-line-atrocities that are possible. I'd stick with this one. Commented Jan 2, 2014 at 13:56
  • @Maerlyn I know I could meddle with DQL to get the resulting array, but in this question I was interested if thats the easiest/most clean way to remap array keys. Commented Jan 2, 2014 at 15:26
  • @Wrikken hi, since I could not find (and noone posted) a better or shorter alternative, I'd gladly accept your comment if you post it as an answer Commented Jan 12, 2014 at 16:50

1 Answer 1

2

It seems there is no shorter/better way than the one posted in the question.

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

Comments

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.