Wednesday, 29 August 2018

PHP creating a multidimensional array from a single array

I have a array list of staff in single array and I am trying to make that multi-dimension based on line manager. So in my example below Miriam Wood manages Alan Haworth and Guy Kahane, and Guy Kahane manages Matthew Baum and Rebecca Roache based on Line Manger field. So my current array is looking some like this.

Looking to do some from
  1. Miriam Wood - no line manager
  2. Alan Hanworth - line manager -> id 1
  3. Guy Kahane - line manager -> id 1
  4. Matthew Baum - line manager -> id 3
  5. Rebecca Roache - line manager -> id 3
to
  • Miriam Wood
    • Alan Hanworth
    • Guy Kahane
      • Matthew Baum
      • Rebecca Roache
[98] => Array ([Id] => 1, [Name] => Miriam Wood, [Line Manager] => None)

[99] => Array([Id] => 2, [Name] => Alan Haworth, [Line Manager] => 1)

[105] => Array([Id] => 3, [Name] => Guy Kahane, [Line Manager] => 1)

[106] => Array([Id] => 4, [Name] => Matthew Baum, [Line Manager] => 3)

[107] => Array([Id] => 5, [Name] => Rebecca Roache, [Line Manager] => 3)

And I would like to change it to
(
 [98] => Array
(
   [Id] => 1
   [Name] => Miriam Wood
   [Line Manager] => None
   [Staffs] => Array
(
    [99] => Array
    (
        [Id] => 2
        [Name] => Alan Haworth
        [Line Manager] => 1
    )

    [105] => Array
    (
        [Id] => 3
        [Name] => Guy Kahane
        [Line Manager] => 1
        [staffs] => Array
        (
            [106] => Array
            (
                [Id] => 4
                [Name] => Matthew Baum
                [Line Manager] => 3
            )

            [107] => Array
            (
                [Id] => 5
                [Name] => Rebecca Roache
                [Line Manager] => 3
            )
        )
    )
)

) )

this is simple example.
$head = array("id">1,"name"=>"Harshana","servents"=>array(
"s1"=>array("id">1,"name"=>"abc"),
"s2"=>array("id">2,"name"=>"sdf"),
"s3"=>array("id">3,"name"=>"fgh")
));
print_r($head);
echo "<hr />";
print_r($head["servents"]);
echo "<hr />";
print_r($head["servents"]["s1"]);
echo "<hr />";
$s1 = $head["servents"]["s1"];
echo "servent 1 name :".$s1["name"];

hope you can get idea for your matter.

0 comments:

Post a Comment