user889349 user889349 - 7 months ago 27
PHP Question

Working with arrays - clone

I have an array:

$obj = Array
(
[0] => stdClass Object
(
[id] => 1
[qty] => 2
)

[1] => stdClass Object
(
[id] => 2
[qty] => 1
)
);


How can I based on the qty can convert the array to this:

$obj2 = Array
(
[0] => stdClass Object
(
[id] => 1
[qty] => 1
)

[1] => stdClass Object
(
[id] => 1
[qty] => 1
)
[2] => stdClass Object
(
[id] => 2
[qty] => 1
)
);


Thanks!

Answer

This should work:

<?php
$obj = array(
    0 => (object) array(
        'id' => 1,
        'qty' => 2
    ),
    1 => (object) array(
        'id' => 2,
        'qty' => 1
    )
);

$obj2 = array();

foreach($obj as $v)
{
    if($v->qty > 1)
    {
        while($v->qty > 0)
        {
            $obj2[] = (object) array('id'=>$v->id, 'qty'=>1);
            --$v->qty;
        }
    }
    else
    {
        $obj2[] = $v;
    }
}

print_r($obj2);
Comments