1

I would like to split an array of objects into multiple arrays by key=>value, but I couldn't figure it out how.

I have an array like this:

Array => (
 [0]=>stdClass Object(
  [id]=>1
  [title]=> Title1
  [content]=>Content1
  [cat]=>Cat1
  [date]=>20140910
 )
 [1]=>stdClass Object(
  [id]=>2
  [title]=> Title2
  [content]=>Content2
  [cat]=>Cat2
  [date]=>20140910
 )
 [2]=>stdClass Object(
  [id]=>3
  [title]=> Title3
  [content]=>Content3
  [cat]=>Cat1
  [date]=>20140910
 )
)

and I would like to split this by "cat"=>"value" and create an array like this

Array => (
 [Cat1] => Array(
  [0] => Array(
   [id]=>1
   [title]=> Title1
   [content]=>Content1
   [cat]=>Cat1
   [date]=>20140910
  )
  [1] => Array(
   [id]=>3
   [title]=> Title3
   [content]=>Content3
   [cat]=>Cat3
   [date]=>20140910
  )
 )
 [Cat2] => Array(
  [0] => Array(
   [id]=>2
   [title]=> Title2
   [content]=>Content2
   [cat]=>Cat2
   [date]=>20140910
  )
 )
)

So this is what I'm trying to do but I couldn't.

2 Answers 2

5

You can use casting. Use (array) before object. An example here..

$newArr = array();
foreach($obj as $val){
    $newArr[$val->cat][] = (array)$val;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this worekd! I didn't thought that the solution would be so simple. I tend to over think things :)
2
$array = array();
foreach ($objects as $k => $v) {
 if (!isset($array[$v->cat])) {
   $array[$v->cat] = array();
 } 
 $array[$v->cat][] = (array) $v;
}

1 Comment

No need for !isset($array[$v->cat]) .., just $array[$v->cat][] = .. will do just fine.

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.