Din array cu obiecte in array multidimensional - PHP

Salutare,

Am un array pe care il primesc din SQL de forma:

[0]=>
  object(stdClass) {
    ["idParinte"] => 1
    ["denumireParinte"] => "Familia Popescu"
    ["nivel1"] => 1
    ["idCopil"] => 20
    ["denumireCopil"] => "Ionica"
    ["nivel2"] => 2
  }
[2]=>
  object(stdClass) {
    ["idParinte"] => 1
    ["denumireParinte"] => "Familia Popescu"
    ["nivel1"] => 1
    ["idCopil"] => 21
    ["denumireCopil"] => "Mirel"
    ["nivel2"] => 2
  }
[3]=>
  object(stdClass) {
    ["idParinte"] => 1
    ["denumireParinte"] => "Familia Popescu"
    ["nivel1"] => 1
    ["idCopil"] => 22
    ["denumireCopil"] => "Victor"
    ["nivel2"] => 2
  }
[4]=>
  object(stdClass) {
    ["idParinte"] => 2
    ["denumireParinte"] => "Familia Pop"
    ["nivel1"] => 1
    ["idCopil"] => 30
    ["denumireCopil"] => "Marius"
    ["nivel2"] => 2
  }
[5]=>
  object(stdClass) {
    ["idParinte"] => 2
    ["denumireParinte"] => "Familia Pop"
    ["nivel1"] => 1
    ["idCopil"] => 31
    ["denumireCopil"] => "Bogdan"
    ["nivel2"] => 2
  }

Cum pot procesa array-ul ca la final sa il pot afisa intr-un tabel de forma

+-----------------+
| Familia Popescu |
+-----------------+
| Ionica          |
| Mirel           |
| Victor          |
+-----------------+
| Familia Pop     |
+-----------------+
| Marius          |
| Bogdan          |
+-----------------+

Multumesc!

Dac─â lista este ordonat─â dup─â numele de familie, pur ┼či simplu o re┼úii ┼či o afi┼čezi doar c├ónd se schimb─â, ceva ├«n genul ─âsta:

$last = "";
foreach($persons as $person)
{
    if($person->denumireParinte != $last)
    {
        echo $person->denumireParinte, "\n";
    }

    echo $person->denumireCopil, "\n";
    $last = $person->denumireParinte;
}

Dac─â vrei s─â compui un array, pur ┼či simplu folose┼čti asociativitatea:

$result = array();
foreach($persons as $person)
{
    $result[$person->denumireParinte][] = $person->denumireCopil;
}

Iar ca s─â afi┼čezi array-ul:

foreach($result as $family => $members)
{
    echo $family, "\n";

    foreach($members as $member)
    {
        echo $member, "\n";
    }
}
1 Like