JessycaFrederick
JessycaFrederick

Reputation: 408

PHP array not setting custom key in a foreach loop

I'm looping through a database object returned by MySQL in CodeIgniter 2.x (PHP). The array $gifts has been declared outside the loop before it begins.

There is an inner loop and an outer loop. The outer loop generates the second array example below. The inner loop generates the problem array.

In LINE 2, $i['gifts'][$row->id_gift] correctly setting the keys with the desired id $row->id_gift. In LINE 1, it is not. The array key is being assigned numerically in order from 0-n as if it were being set with $gifts[][$sd] = $row->$sd.

Any thoughts on why?

$query = $this->db->get();

if ($query->num_rows() > 0)
{
    foreach ($query->result() as $row)
    {
        foreach ($select_details as $sd)
        {
           $gifts[$row->id_gift][$sd] = $row->$sd; // LINE 1
           $i['gifts'][$row->id_gift] = array('merchant_rank'=>$i['merchant_rank'],'rank'=>$row->rank); // LINE 2
        }
    }                
}

$select_details = array('id_gift','id_group','rank');

Array (LINE 1) output sample:

Array ( 
    [0] => 
    Array ( 
        [id_gift] => 392 
        [id_group] => 244 
        [rank] => 1 
    ) 
    [1] => Array ( 
        [id_gift] => 287 
        [id_group] => 239 
        [rank] => 1 
    ) 
    [2] => Array ( 
        [id_gift] => 264 
        [id_group] => 4 
        [rank] => 1)
)

Array (LINE 2) output sample (note the correct keys in the gifts array):

Array (
    [0] => Array
    (
        [id] => 49
        [id_group] => 49
        [id_merchants] => 116
        [gifts] => Array
        (
            [392] => Array
            (
                [merchant_rank] => 1
                [rank] => 1
            )
            [287] => Array
            (
                [merchant_rank] => 1
                [rank] => 2
            )
            [264] => Array
            (
                [merchant_rank] => 1
                [rank] => 3
            )
        )
    )
)

RESOLVED. See my answer below if you're curious. Thanks for your help @Spartan and @DontPanic.

Upvotes: 1

Views: 392

Answers (1)

JessycaFrederick
JessycaFrederick

Reputation: 408

Okay, I figured out the problem. And the more experienced programmers among you might not be all that surprised.

Later in the script I'm using a multidimensional array sort that's destroying the keys. I'm sure there's a way to prevent that, but that's not pertinent here.

usort($gifts, function($a, $b) { return $a['rank'] - $b['rank']; });

Upvotes: 1

Related Questions