3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php $bookInfo = array( 0 => array("bookId" => "1", "bookName" => "Book 1", "authorId" => 1, "authorName" => "Author 1") , 1=> array("bookId" => "1", "bookName" => "Book 1", "authorId" => 2, "authorName" => "Author 2") , 2=> array("bookId" => "2", "bookName" => "Book 2", "authorId" => 3, "authorName" => "Author 3") , 3=> array("bookId" => "3", "bookName" => "Book 3", "authorId" => 4, "authorName" => "Author 4") ); print_r($bookInfo); $newBookInfo = []; $newBookKey = []; $newKey = 0; foreach($bookInfo as $bookKey => $bookValue){ if(!in_array($bookValue["bookId"],$newBookKey)){ ++$newKey; $newBookInfo[$newKey]["bookId"] = $bookValue["bookId"]; $newBookInfo[$newKey]["bookName"] = $bookValue["bookName"]; } $newBookInfo[$newKey]["authorName"][$bookKey] = $bookValue["authorName"]; $newBookKey[] = $bookValue["bookId"]; } print_r($newBookInfo);
Output for 5.5.0 - 5.6.30, hhvm-3.12.14 - 3.22.0, 7.0.0 - 7.2.11
Array ( [0] => Array ( [bookId] => 1 [bookName] => Book 1 [authorId] => 1 [authorName] => Author 1 ) [1] => Array ( [bookId] => 1 [bookName] => Book 1 [authorId] => 2 [authorName] => Author 2 ) [2] => Array ( [bookId] => 2 [bookName] => Book 2 [authorId] => 3 [authorName] => Author 3 ) [3] => Array ( [bookId] => 3 [bookName] => Book 3 [authorId] => 4 [authorName] => Author 4 ) ) Array ( [1] => Array ( [bookId] => 1 [bookName] => Book 1 [authorName] => Array ( [0] => Author 1 [1] => Author 2 ) ) [2] => Array ( [bookId] => 2 [bookName] => Book 2 [authorName] => Array ( [2] => Author 3 ) ) [3] => Array ( [bookId] => 3 [bookName] => Book 3 [authorName] => Array ( [3] => Author 4 ) ) )