0

I have an array that look like this

(
 0 => array( id     => '1',
             title  => 'some title',
             type   => 'fiction'
           )
 1 => array( id    => '2',
             title  => 'some title',
             type   => 'fiction'
           )
 2 => array( id     => '3',
             title  => 'some title',
             type   => 'Romance'
           )
)

I am trying to restructure it to be more like the following

(
 'fiction' => array( 0 => array( id     => '1',
                                 title  => 'some title',
                               )
                     1 => array( id     => '2',
                                 title  => 'some title'
                               ), 
 'Romance' => array( 0 => array( id     => '2',
                                 title  => 'some title'
                               )
)

I tried different function but cannot get it to work. Any help would be greatly appreciated. Thank you.

2

3 Answers 3

1
$a1 = array(
 0 => array( 'id'     => '1',
             'title'  => 'some title',
             'type'   => 'fiction'
           ),
 1 => array( 'id'    => '2',
             'title'  => 'some title',
             'type'   => 'fiction'
           ),
 2 => array( 'id'     => '3',
             'title'  => 'some title',
             'type'   => 'Romance'
           )
);
$a2 = array();
foreach($a1 as $item)
{

    $a2[$item['type']][] = array('id'=> $item['id'], 'title'=> $item['title']);
}
Sign up to request clarification or add additional context in comments.

1 Comment

This solution works just fine. Items from the initial array are grouped by type perfectly. Cheers Friend
0

What I have done in the past is to loop through and create a new array using your desired value as a new key:

$newList = array();
foreach ($yourArray as $book) {
  $newList[$book['title']][] = $book;
  // Optionally unset 'title' from $book if it matters.
}

There is probably a more elegant way...

Comments

0

lets assume first array is $array1 and second is $array2,then try this :

 $array1 = array(
 0 => array(  'id'     => '1',
                    'title'  => 'some title',
                    'type'   => 'fiction'
            ),
 1 => array( 'id'    => '2',
             'title'  => 'some title',
             'type'   => 'fiction'
           ),
 2 => array( 'id'     => '3',
             'title'  => 'some title',
             'type'   => 'Romance'
           )
);
$array2 = array();
foreach($array1 as $each)
    $array2[$each['type']][] = array_slice($each,0,2);

print_r($array1);
print_r($array2);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.