note 106480 modified in function.array-unique by danbrown

From: Date: Tue, 15 Nov 2011 16:30:20 +0000
Subject: note 106480 modified in function.array-unique by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-184481@lists.php.net to get a copy of this message
Lets say that you want to capture unique values from multidimensional arrays and flatten them in 0 depth. i.e. <?php $tmp = array( 'a' => array( 1,2,3,4 ), 'b' => array( 'c' => array( 4,5,6,7 ) ) ); ?> will return with array_flat( $tmp ) --> array( 1,2,3,4,5,6,7 ); I hope that the function will help someone <?php /** * @params : $a array the recursion array * : $s array storage array * : $l integer the depth level * */ if( !function_exists( 'array_flat' ) ) { function array_flat( $a, $s = array( ), $l = 0 ) { # check if this is an array if( !is_array( $a ) ) return $s; # go through the array values foreach( $a as $k => $v ) { # check if the contained values are arrays if( !is_array( $v ) ) { # store the value $s[ ] = $v; # move to the next node continue; } # increment depth level $l++; # replace the content of stored values $s = array_flat( $v, $s, $l ); # decrement depth level $l--; } # get only unique values if( $l == 0 ) $s = array_values( array_unique( $s ) ); # return stored values return $s; } # end of function array_flat( ... } ?> --was-- Lets say that you want to capture unique values from multidimensional arrays and flatten them in 0 depth. i.e. $tmp = array( 'a' => array( 1,2,3,4 ), 'b' => array( 'c' => array( 4,5,6,7 ) ) ); will return with array_flat( $tmp ) --> array( 1,2,3,4,5,6,7 ); I hope that the function will help someone /** * @params : $a array the recursion array * : $s array storage array * : $l integer the depth level * */ if( !function_exists( 'array_flat' ) ) { function array_flat( $a, $s = array( ), $l = 0 ) { # check if this is an array if( !is_array( $a ) ) return $s; # go through the array values foreach( $a as $k => $v ) { # check if the contained values are arrays if( !is_array( $v ) ) { # store the value $s[ ] = $v; # move to the next node continue; } # increment depth level $l++; # replace the content of stored values $s = array_flat( $v, $s, $l ); # decrement depth level $l--; } # get only unique values if( $l == 0 ) $s = array_values( array_unique( $s ) ); # return stored values return $s; } # end of function array_flat( ... } http://php.net/manual/en/function.array-unique.php

« previous php.notes (#184481) next »