note 124460 added to function.array-reduce

From: Date: Mon, 02 Dec 2019 08:28:28 +0000
Subject: note 124460 added to function.array-reduce
Groups: php.notes 
Request: Send a blank email to php-notes+get-213369@lists.php.net to get a copy of this message
Array reduce offers a way to transform data. Please look at the array below. The array has 4 nested array's. The nested array's have the same keys. Only the value is different. This code transforms the whole array. See below. $array = array( 0 => array('id' => '100', 'name' => 'Henk', 'age' => '30'), 1 => array('id' => '101', 'name' => 'Piet', 'age' => '33'), 2 => array('id' => '102', 'name' => 'Wim', 'age' => '43'), 3 => array('id' => '103', 'name' => 'Jaap', 'age' => '53'), ); $arr = array_reduce($array, function($carry, $item){ $arr = array( 'id' => $item['id'], 'value' => $item['name'], ); $id = $item['id']; $carry[$id] = $arr; return $carry; }, array()); var_dump($arr); // OUTPUT array (size=4) 100 => array (size=2) 'id' => string '100' (length=3) 'value' => string 'Henk' (length=4) 101 => array (size=2) 'id' => string '101' (length=3) 'value' => string 'Piet' (length=4) 102 => array (size=2) 'id' => string '102' (length=3) 'value' => string 'Wim' (length=3) 103 => array (size=2) 'id' => string '103' (length=3) 'value' => string 'Jaap' (length=4) ---- Server IP: 208.43.231.9 Probable Submitter: 185.85.3.195 (proxied: 92.111.159.162) ---- Manual Page -- http://php.net/manual/en/function.array-reduce.php Edit -- https://master.php.net/note/edit/124460 Del: integrated -- https://master.php.net/note/delete/124460/integrated Del: useless -- https://master.php.net/note/delete/124460/useless Del: bad code -- https://master.php.net/note/delete/124460/bad+code Del: spam -- https://master.php.net/note/delete/124460/spam Del: non-english -- https://master.php.net/note/delete/124460/non-english Del: in docs -- https://master.php.net/note/delete/124460/in+docs Del: other reasons-- https://master.php.net/note/delete/124460 Reject -- https://master.php.net/note/reject/124460 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#213369) next »