2

I am trying to sort this array in php:

Array
(
    [Levi Self] => Array
        (
            [0] => Portraits
            [1] => Abstract
        )

    [Portraits] => Array
        (
            [0] => Megan
        )

    [Abstract] => Array
        (
            [0] => Locks
        )

)

To look like this:

Array
(
    [Levi Self] => Array
        (
            [Portraits] => Array
               (
                 [0] => Megan
               )

            [Abstract] => Array
               (
                 [0] => Locks
               )
        )
)

Which, basically, removes the duplicate items "Portraits" and "Abstract", as they are already the keys for the array to begin with, along with being items under the first key, "Levi Self". Is there any way to do this? Thanks, Levi Self

Levi Self
  • 333
  • 1
  • 3
  • 5
  • 1
    Where is the data coming from? Seems like changing the compilation makes more sense than doctoring the problem, if it's possible. Also seems like it's a SQL result, though could be wrong? – Brad Christie Feb 21 '11 at 01:56
  • The data is coming from a SQL result, as you can see here (different question) [link](http://stackoverflow.com/questions/5053857/php-multi-dimensional-array-from-mysql-result) – Levi Self Feb 21 '11 at 02:39
  • Mind if you post the SQL that produce this result? – Ibrahim AshShohail Feb 21 '11 at 02:55
  • @Ibrahim: The query: `$query = mysql_query( "SELECT * FROM `table` WHERE `uid`='1' ORDER BY `id` DESC");` and formating the array to the one above: `foreach ($list as $key => $arr) { $result[ $arr['parent'] ] [] = $arr['title']; }` – Levi Self Feb 21 '11 at 03:07
  • When not make the parent field the id of the parent row? This way you can achieve what you want through SQL. – Ibrahim AshShohail Feb 21 '11 at 03:11

1 Answers1

1

$priKey = "Levi Self";
$arr = array(
    "Levi Self" => array("Portraits","Abstract"),
    "Portraits" => array("Megan"),
    "Abstract" => array("Locks")
);

function rearrangeData($primaryKey,$myArr){
    foreach($myArr[$primaryKey] as $key => $value){
        $myArr[$primaryKey][$value] = $myArr[$value];
        unset($myArr[$primaryKey][$key]);
        unset($myArr[$value]);
    }

    return $myArr;
}

$arr2 = rearrangeData($priKey, $arr);

print_r($arr); //what you started with
print_r($arr2); //what you want