[Solved] Listdata Not Getting All Arecord Fields Into The Array

Hello,

I’m getting some values from an Active Record, however, I need them straight as an array and not directly as an Active Record object.

Therefore, I’ve remembered to use the CHtml::listData to transform it to what I need to, a bi-dimensional array.

The problem is that it will just pass one of the values to the array. Why?

Code with example of what I’m trying to do below:


    <?php

    $categories = PageCategory::model()->findAllByAttributes( array('page_id'=>1) );

                foreach($categories as $c)

                    echo $c->page_id . ' - '. $c->category_id.'<br />';

    /* OUTPUT

    1 - 1

    1 - 2

    */

     


// DOES NOT WORK

    $categories = CHtml::listData($categories, 'page_id', 'category_id');

     

    echo '<pre>';print_r($categories);echo '</pre>';

    /* OUTPUT

    Array

    (

        [1] => 2

    )




    SHOULD PASS SOMETHING LIKE


    Array

    (

        [1] => 1

        [1] => 2

    )   

   */

    ?>

The array key is being overwritten because the page_id is 1. Can you use a unique ID?

Hi, thanks for your reply.

I can’t, as this is a many-to-many relationship table.

Damn, probably I was half-sleeping when I read your answer.

Yesterday in the evening I’ve came to that conclusion in a similar error I’ve had in another project. As page_id is always the same, array index will always be the same and it will be overwritten - just like you said.

I’ve corrected this doing something like:


    $categories = PageCategory::model()->findAllByAttributes( array('page_id'=>1) );


    $categories_array = array();

    

    foreach($categories as $c)

        $categories_array[] = array( $c->page_id => $c->category_id );



(i’m not at home right now and I don’t have access to the fixed version of the code, but I think it is as I’ve written it)

Basically, instead of creating a bi-dimensional array, I had to create a multi-dimensional one to create a one more level of abstraction, so page_ids don’t collide.

So, solved!