johnny538
johnny538

Reputation: 625

How to get child from array with dynamic parent in php

Array
(
[123] => Array
    (
        [shipment_id] => 123456
    )
)

I need the value from shipment_id, but I don't always know the array name '123' since it's different for each shipment.

I'm trying:

$array = $order->get_meta('_shipments');
echo $array[123]['shipment_id']; <- Works
echo $array[0]['shipment_id']; <- Doesn't work
echo $array['']['shipment_id']; <- Doesn't work
echo $array[]['shipment_id']; <- Doesn't work

Upvotes: 0

Views: 155

Answers (2)

prasanna puttaswamy
prasanna puttaswamy

Reputation: 987

You can use array_column like array_column($array,'column_name'), this results in getting all the values of column from multi-dimensional array.

<?php
$testArray = array(array('ids'=>1,'q'=>'hi'),array('ids'=>2,'q'=>'test')); 
$ids = array_column($testArray,'ids');
print_r($ids);
?>

Upvotes: 0

Eddie
Eddie

Reputation: 26854

You can use array_values

This will return all the values of an array

$arr = array (
    "123" => array (
        "shipment_id" => 123456
    )
);

$arr = array_values($arr); //Convert assoc array to simple array

echo "<pre>";
print_r( $arr );
echo "</pre>";

This will result to:

Array
(
    [0] => Array
        (
            [shipment_id] => 123456
        )

)

You can now access as $arr[0]['shipment_id']

Doc: http://php.net/manual/en/function.array-values.php

Upvotes: 1

Related Questions