Friday 26 July 2013

Getting Random values from Array

To Get Random Values from Array :

$arr = array("a"=>"apple","b"=>"ball","c"=>"cat","d"=>"dog" );

shuffle($arr);

Eg :

Before Shuffle :

Array ( [a] => apple [b] => ball [c] => cat [d] => dog )

After Shuffle :

Array ( [0] => ball [1] => cat [2] => apple [3] => dog1 )   // will change order every time we refresh the page


To Pick Random Key from Array :

Eg : picking 2 random keys from  an array

$val = array_rand($arr,2);

print_r($val);

Array ( [0] => b [1] => d )




Converting Object to Array


Convert all objects to Array :

function objectToArray( $object ) {
    if( !is_object( $object ) && !is_array( $object ) ) {
        return $object;
    }
    if( is_object( $object ) ) {
        $object = (array) $object;
    }
    return array_map( 'objectToArray', $object );
}

(or)


function object_to_array($data)
{
    if (is_array($data) || is_object($data))
    {
        $result = array();
        foreach ($data as $key => $value)
        {
            $result[$key] = object_to_array($value);
        }
        return $result;
    }
    return $data;
}


Converting First object to Array :


function app_convertObjectToArray($objectValue) {
if (is_array ( $objectValue )) {
$arrayValue = $objectValue;
} else {
$arrayValue = array ();
if (isset ( $objectValue )) {
array_push ( $arrayValue, $objectValue );
}
}
return $arrayValue;
}