我想通过 key=>value 将一组对象拆分为多个数组,但我不知道怎么做。
我有一个这样的数组:
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
)
)
Run Code Online (Sandbox Code Playgroud)
我想用“cat”=>“value”分割它并创建一个这样的数组
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
)
)
)
Run Code Online (Sandbox Code Playgroud)
所以这就是我想要做的,但我做不到。
您可以使用casting. (array)在对象之前使用。这里有一个例子..
$newArr = array();
foreach($obj as $val){
$newArr[$val->cat][] = (array)$val;
}
Run Code Online (Sandbox Code Playgroud)