1

I have one large multidimensional array, which I got from database with picture locations

Array
(
    [0] => Array
        (
            [name] => 01.jpg
            [album] => /images/beach
        )

    [1] => Array
        (
            [name] => 02.jpg
            [album] => /images/beach
        )
    [2] => Array
        (
            [name] => 03.jpg
            [album] => /images/home
        )
)

i am trying to split it into smaller arrays that match the albums, as below:

Array
(
    [0] => Array
        (
            [name] => 01.jpg
            [album] => /images/beach
        )

    [1] => Array
        (
            [name] => 02.jpg
            [album] => /images/beach
        )
)
Array
(
    [0] => Array
        (
            [name] => 03.jpg
            [album] => /images/home
        )
 )

what would be a good way to go about it? i am thinking of shifting the first value into a new array until I reach the end but there must be a more effective way.

kamal pal
  • 4,187
  • 5
  • 25
  • 40
TMpic
  • 73
  • 8
  • You might construct the desirable structure while fetching the rows from database: `while ($row = $conn->fetch_assoc()) { $result [$row['album']] = $row; }` – Ruslan Osmanov May 12 '16 at 13:42
  • Both arrays are the same? Could you rephrase your Question, please? – Poiz May 12 '16 at 13:42
  • Can you also add a query that you're retrieving the data with? It might be easier to sort it by albums in the time you're getting the data from the database. And also the code how you're constructing the data. – Richard May 12 '16 at 13:43
  • If you want to do it the more difficult way, here's the answer http://stackoverflow.com/questions/7574857/group-array-by-subarray-values – Richard May 12 '16 at 13:43

2 Answers2

0

I would do it this way.

$albums = array();
foreach ($dbrows as $dbrow) {
    $albums[$dbrow['album']][] = $dbrow;
}
unset($dbrows);
var_dump($albums);
Xyz
  • 5,955
  • 5
  • 40
  • 58
0

You can create a new array using album as key, which you need to group with, and thereafter updated keys using array_values if needed.

<?php
$arrays = array
(
    '0' => array
        (
            'name' => '01.jpg',
            'album' => '/images/beach'
        ),

    '1' => array
        (
            'name' => '02.jpg',
            'album' => '/images/beach'
        ),
    '2' => array
        (
            'name' => '03.jpg',
            'album' => '/images/home'
        )
);
$results = array();
foreach($arrays as $array){
    $results[$array['album']][] = $array;
}
$results = array_values($results);
print_r($results);

Demo: https://eval.in/569788

kamal pal
  • 4,187
  • 5
  • 25
  • 40