OM The Eternity
OM The Eternity

Reputation: 16244

How to reindex an array of objects?

I am working in PHP with array iteration.

I have a multidimensional array like this:

Array
(
    [1] => stdClass Object
        (
            [id] => 1
            [comments] => Testing the Data
            [stream_context_id] => 5
            [stream_entity_id] => 
            [class_id] => 1
            [parent_id] => 0
            [learnt_count] => 
            [rating_count] => 
            [abused_count] => 
            [created_by] => 1
            [created_datetime] => 
            [stream_context] => comments
            [name] => 
            [upload_path] => 
            [uploadby] => 
            [upload_time] => 
        )

    [2] => stdClass Object
        (
            [id] => 2
            [comments] => Testing the Data
            [stream_context_id] => 5
            [stream_entity_id] => 
            [class_id] => 1
            [parent_id] => 0
            [learnt_count] => 
            [rating_count] => 
            [abused_count] => 
            [created_by] => 1
            [created_datetime] => 
            [stream_context] => comments
            [name] => 
            [upload_path] => 
            [uploadby] => 
            [upload_time] => 
        )

)

Here the first index values i.e. 1 and 2 are the ids mentioned in their corresponding arrays.

I want the same multidimensional array with index values a 0 and 1 and so on.. i.e. the usual format of an array.

Upvotes: 0

Views: 148

Answers (3)

Eskil Mjelva Saatvedt
Eskil Mjelva Saatvedt

Reputation: 547

This does look like a multidimentional array as you have a named array holding objects.

Your array is currently:

$a = array('1'=>Object, '2'=>Object);

Instead of:

$a = array('1'=>array('id'=>'1', 'comment'=>'some comment'), '2'=>array());
$b = array();
foreach($a as $key=>$val){
    $b[] = $val;
}

Upvotes: 1

Yoshi
Yoshi

Reputation: 54659

Don't know if this is what you meant, but maybe...:

$reindexedArray = array_values($yourArray);

If you also want to convert the stdClass objects to arrays, try:

$reindexedAndArrayifiedArray = array_values(array_map(function ($entry) {
    return (array)$entry;
}, $yourArray));

Upvotes: 7

Gus
Gus

Reputation: 7349

Using array_merge() with a blank array - will renumber numeric indexes:

$result = array_merge(Array(), $your_array_here) ;

Upvotes: 1

Related Questions