Pages

Showing posts with label function. Show all posts
Showing posts with label function. Show all posts

22 Jun 2013

php in_array function

in_arrayChecks if a value exists in an array

bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )



Example #1 in_array() example
<?php
$os 
= array("Mac""NT""Irix""Linux");
if (
in_array("Irix"$os)) {
    echo 
"Got Irix";
}
if (
in_array("mac"$os)) {
    echo 
"Got mac";
}
?>

14 Jun 2013

Convert XML to CSV with PHP


PROBLEM : 
I'm using the following code to convert my XML file to a CSV format. Unfortunately, it seems to not be recognizing each entry in the XML and so the XML file ends up being blank.

An example of my XML file is below... Solution :

Sorting Deep Multidimentional array PHP


Given the following array:
Array 
(
    [0] => Array
        (
            [0] => Array
                (
                    [key1] => var1
                    [key2] => var2
                    [sortOnMe] => 4
                )

            [1] => N/A
            [2] => N/A
            [3] => N/A
        )

    [1] => Array
        (
            [0] => Array
                (
                    [key1] => var1
                    [key2] => var2
                    [sortOnMe] => 2
                )

            [1] => N/A
            [2] => N/A
            [3] => N/A
        )
)
Given the following array:
Array 
(
    [0] => Array
        (
            [0] => Array
                (
                    [key1] => var1
                    [key2] => var2
                    [sortOnMe] => 4
                )

            [1] => N/A
            [2] => N/A
            [3] => N/A
        )

    [1] => Array
        (
            [0] => Array
                (
                    [key1] => var1
                    [key2] => var2
                    [sortOnMe] => 2
                )

            [1] => N/A
            [2] => N/A
            [3] => N/A
        )
)
How can I sort this array considering the key I want is deep in the structure?
I assume usort but not sure what to pass into the function?
 

Ans:

usort($arr, "mysortfunc");

function mysortfunc($a, $b)
{
    if ($a[0]['sortOnMe'] == $b[0]['sortOnMe'])
    {
        return 0;
    }
    else
    {
        return ($a[0]['sortOnMe'] < $b[0]['sortOnMe']) ? -1 : 1;
    }
}