[英]how to put a different objects inside each array element of an array in php?
I have two arrays, eg 我有两个数组,例如
$mainArray = array('a','b','c','d','e','f','g');
$subArray = it contains an array of objects eg $ subArray =它包含一个对象数组,例如
array( objec1, objec2, object3, object4) ...
within each of the objects, holds the value that matches one of the keys in the $mainArray. 在每个对象中,保存与$ mainArray中的键之一匹配的值。
my Question now is, how am i gonna match and put the correct objects to the mainArray, so that it should appear like this eg 我现在的问题是,我该如何匹配并将正确的对象放入mainArray,这样它应该看起来像这样,例如
$mainArray = array('a'=> array(object3,object2), 'b' => array(object4,object1));
$result = array();
foreach ($subArray as $obj) {
if (!isset($result[$obj->keyOfMainArray])) {
$result[$obj->keyOfMainArray] = array();
}
$result[$obj->keyOfMainArray][] = $obj;
}
Assuming val
is your object
's property 假设
val
是object
的属性
$mainArray = array('a','b','c','d','e','f','g');
$subArray = array(...);
$result = array();
foreach($subArray as $object) {
$result[$object->val][] = $object;
}
Example result 结果示例
Array
(
[a] => Array
(
[0] => stdClass Object
(
[val] => a
)
[1] => stdClass Object
(
[val] => a
)
)
[b] => Array
(
[0] => stdClass Object
(
[val] => b
)
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.