BigToach.com

PHP Snippets

array_pivot

Information

(PHP Version >= 3)
Functions used in this snippet: is_array, count, is_null, array_key_exists, elseif.

Description

array array_pivot( array array, str key, str value )

array_pivot will take a multidimensional associative array and return a single dimension associative array with the keys from the column $key and the values from the column $value. If $key is set to null then it will return a regular array with integer keys.

Snippet

<?php
function array_pivot($array$key$value) {
    if(!
is_array($array))
        return 
false;
    if(
count($array) === 0)
        return array();
    
$ret = array();
    foreach(
$array as $ray) {
        if(
is_null($key)) {
            if(
array_key_exists($value$ray)) {
                
$ret[] = $ray[$value];
            }
        } elseif(
array_key_exists($key$ray) && array_key_exists($value$ray)) {
            
$ret[$ray[$key]] = $ray[$value];
        }
    }
    return 
$ret;
}
?>

Example

array_pivot Can be used in the following way:

<?php
$array 
= array(
    array(
        
'id' => '1',
        
'name' => 'Scott',
        
'email' => 'fake@test.com'
    
),
    array(
        
'id' => '4',
        
'name' => 'John',
        
'email' => 'john@test.com'
    
),
    array(
        
'id' => '56',
        
'name' => 'Chris',
        
'email' => 'chris@test.com'
    
)
);

print_r(array_pivot($array'id''name'));
/*
Array
(
    [1] => Scott
    [4] => John
    [56] => Chris
)
*/
print_r(array_pivot($arraynull'email'));
/*
Array
(
    [0] => fake@test.com
    [1] => john@test.com
    [2] => chris@test.com
)
*/
?>

Added on Dec 12th at 7 pm by Scott - 0 Comments


0 Responses to array_pivot

Name:

Site or Mail:

Comment:

To try to reduce the ammount of spam, please enter the word GOOSE in the following form

Security Code: