0

I have two arrays, e.g

$mainArray = array('a','b','c','d','e','f','g');

$subArray = it contains an array of objects e.g

array( objec1, objec2, object3, object4) ...

within each of the objects, holds the value that matches one of the keys in the $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 e.g

$mainArray = array('a'=> array(object3,object2), 'b' => array(object4,object1));
9
  • Iterate over $subArray and fill the result array Commented Dec 19, 2013 at 3:10
  • which result array are you referring to ? Commented Dec 19, 2013 at 3:11
  • The one that you get as a result of the operation Commented Dec 19, 2013 at 3:12
  • 1
    How do you access this value that is stored in each object? In other words, what test can be done to know that object3 and object2 belong to a? Commented Dec 19, 2013 at 3:12
  • @Crackertastic, need to iterate via foreach, each of the object in order to get the value like $val->keyOfMainArray , it seem complicated the way i see it Commented Dec 19, 2013 at 3:13

2 Answers 2

2
$result = array();
foreach ($subArray as $obj) {
    if (!isset($result[$obj->keyOfMainArray])) {
        $result[$obj->keyOfMainArray] = array();
    }

    $result[$obj->keyOfMainArray][] = $obj;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Assuming val is your object's property

$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
                )

        )

)

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.