eXtreme eXtreme - 6 months ago 10
PHP Question

Trying to get values of associative array in PHP

I'm have really lame question about PHP arrays, I'm trying to get all values of form[extras][], in this case they are 1,2,3,4, here is the output of print_r($array):

Array
(
[0] => Array
(
[name] => form[pickupDate][day]
[value] => 1
)

[1] => Array
(
[name] => form[pickupDate][month]
[value] => 10
)

[2] => Array
(
[name] => form[pickupTime][hour]
[value] => 0
)

[3] => Array
(
[name] => form[returnDate][day]
[value] => 1
)

[4] => Array
(
[name] => form[returnDate][month]
[value] => 1
)

[5] => Array
(
[name] => form[returnTime][hour]
[value] => 0
)

[6] => Array
(
[name] => form[car]
[value] => 1
)

[7] => Array
(
[name] => form[pickupAddress]
[value] =>
)

[8] => Array
(
[name] => form[agency]
[value] => 1
)

[9] => Array
(
[name] => form[extras][]
[value] => 1
)

[10] => Array
(
[name] => form[extras][]
[value] => 2
)

[11] => Array
(
[name] => form[extras][]
[value] => 3
)

[12] => Array
(
[name] => form[extras][]
[value] => 4
)

[13] => Array
(
[name] => form[specialPrice]
[value] =>
)

)


You can play with my data, by using this JSON string after converting it to PHP array like this:

$request = '[{"name":"form[pickupDate][day]","value":"1"},{"name":"form[pickupDate][month]","value":"8"},{"name":"form[pickupTime][hour]","value":"0"},{"name":"form[returnDate][day]","value":"1"},{"name":"form[returnDate][month]","value":"1"},{"name":"form[returnTime][hour]","value":"0"},{"name":"form[pickupAddress]","value":""},{"name":"form[agency]","value":"1"},{"name":"form[extras][]","value":"1"},{"name":"form[extras][]","value":"2"},{"name":"form[extras][]","value":"3"},{"name":"form[extras][]","value":"4"},{"name":"form[specialPrice]","value":""}]';
$array = json_decode($request,true);


I already tried with this, but it's resulting string(1) "4":



$result = array_column($array, null, 'name')['form[extras][]']['value'];
var_dump($result);

Answer

You have a multidimensional array, this is an array composed by several arrays.

array->[0]-[1]-[2]...  
        |   |
        |   [name]-[value]
        | 
array-> [name]-[value]

That's why you have to go through each element, for instance with this function (you have one already defined in PHP > 5.5.0):

function array_column($array, $value)
{
    $result = array();
    foreach($array as $element)
    {
        $result[] = $element[$value];
    }
    return $result[];
}

Edit: for getting the values of a subset of specific arrays based upon their name:

function getValuesOfTheArraysForExtras($array)
{
    $result = array();
    foreach($array as $element)
    {
        if($element['name']=='form[extras][]')
            $result[] = $element['value'];
    }
    return $result;
}
Comments