note 126639 deleted from function.array-values by cmb

From: Date: Thu, 25 Nov 2021 09:03:05 +0000
Subject: note 126639 deleted from function.array-values by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-217296@lists.php.net to get a copy of this message
Note Submitter: michael chambers AT fast mail D0T C0M ---- # FUNCTION <?PhP /** * Flatten Array * * Flatten a deep multidimensional array into a single dimensional array * keeping all keys and values assignments. * * @category Function * @author Original Author <MichaelChambers@FastMail.com> * @copyright 2021 Michael Chambers * @license PHP License, Version 3.01 http://www.php.net/license/3_01.txt * @license GNU Free Documentation License, Version 1.3 https://www.gnu.org/licenses/fdl-1.3.html * @version 1.0.0 * @since 2021.11.25.1020 * * @param mixed $array Input data array to be flatten. * @param bool $key Ignore, used with in function its self. **/ function array_union($array, $key=null) { if (!is_array($array)) return $array; $a = []; $key = (!empty($key)?$key.'_':''); // Add's joining character foreach ($array as $k => $value) { if ( is_scalar($value) OR is_resource($value) ) $a[$key.$k] = $value; elseif ( is_array($value) ) $a = array_merge( $a, array_union($value,$key.$k) ); } return $a; } ?> # EXAMPLE <?PHP // USAGE EXAMPLES // Array data $dataIN['SetOne'] = 'First Set'; $dataIN['SetTwo'] = array('Second A', 'B'=>'Second B'); $dataIN['SetTen'] = array( 'SubSet' => array('Nil', 1=>'One', 'Two', array('a', 'b', array('c', 'd', 555, true) ) ), array('Last'=>'End') ); $arrayData = array_union($dataIN); // call function var_dump($arrayData); // output data // OR LOOP THROUGH EACH foreach (array_union($dataIN) as $key => $value){ var_dump("$key = $value"); } ?> # BEFORE <?PHP array (size=3) 'SetOne' => string 'First Set' (length=9) 'SetTwo' => array (size=2) 0 => string 'Second A' (length=8) 'B' => string 'Second B' (length=8) 'SetTen' => array (size=2) 'SubSet' => array (size=4) 0 => string 'Nil' (length=3) 1 => string 'One' (length=3) 2 => string 'Two' (length=3) 3 => array (size=3) 0 => string 'a' (length=1) 1 => string 'b' (length=1) 2 => array (size=4) 0 => string 'c' (length=1) 1 => string 'd' (length=1) 2 => int 555 3 => boolean true 0 => array (size=1) 'Last' => string 'End' (length=3) ?> # AFTER <?PHP array (size=13) 'SetOne' => string 'First Set' (length=9) 'SetTwo_0' => string 'Second A' (length=8) 'SetTwo_B' => string 'Second B' (length=8) 'SetTen_SubSet_0' => string 'Nil' (length=3) 'SetTen_SubSet_1' => string 'One' (length=3) 'SetTen_SubSet_2' => string 'Two' (length=3) 'SetTen_SubSet_3_0' => string 'a' (length=1) 'SetTen_SubSet_3_1' => string 'b' (length=1) 'SetTen_SubSet_3_2_0' => string 'c' (length=1) 'SetTen_SubSet_3_2_1' => string 'd' (length=1) 'SetTen_SubSet_3_2_2' => int 555 'SetTen_SubSet_3_2_3' => boolean true 'SetTen_0_Last' => string 'End' (length=3) ?>

« previous php.notes (#217296) next »