如何使用foreach从多维数组创建变量

时间:2019-04-09 09:28:45

标签: php arrays variables multidimensional-array

我正在尝试使用foreach从多维数组创建变量,但是无法访问嵌套数组。

我尝试在当前的foreach命令中再次使用foreach,但我认为数组格式的内容不允许我这样做。

PHP:

$response = curl_exec($cURL);

$result = json_decode($response, true);

$someArray = $result;
foreach ($someArray as $key => $value) {;
}

curl_close($cURL);

print $value["registration"];
print $value["make"];
print $value["model"];
print $value["fuelType"];
print $value["primaryColour"];

这正是我接收阵列的方式。我可以创建用于注册,制造,模型,firstUsedDate,fuelType和primaryColour的变量。

array(
    [0] => array(
        [registration]  => DU11LVA
        [make]          => MINI
        [model]         => MINI(R57)
        [firstUsedDate] => 2011.03.05
        [fuelType]      => Diesel
        [primaryColour] => White

        [motTests]      => array(

            [0] => array(
                [completedDate]  => 2018.04.1116:00:30
                [testResult]     => PASSED
                [expiryDate]     => 2019.04.10
                [odometerValue]  => 45283
                [odometerUnit]   => mi
                [motTestNumber]  => 138359719457

                [rfrAndComments] => array(
                    [0] => array(
                        [text] => Nearside Front Road wheel with a slightly distorted bead rim INSIDE (4.2.A.1a) 
                        [type] => ADVISORY)))

            [1] => array(
                [completedDate]  => 2018.04.1110:22:54
                [testResult]     => FAILED
                [odometerValue]  => 45283
                [odometerUnit]   => mi
                [motTestNumber]  => 652014545840

                [rfrAndComments] => array(
                    [0] => array(
                        [text] => Nearside Front Road wheel with a slightly distorted bead rim INSIDE (4.2.A.1a) 
                        [type] => ADVISORY)
                    [1] => array(
                        [text] => Nearside Front Shock absorber has a serious fluid leak (2.7.3) 
                        [type] => FAIL)))

            [2] => array(
                [completedDate]  => 2017.04.0610:27:08
                [testResult]     => PASSED
                [expiryDate]     => 2018.04.08
                [odometerValue]  => 37579
                [odometerUnit]   => mi
                [motTestNumber]  => 605834707501

                [rfrAndComments] => array())

我正在尝试获取expiryDate和odometerValue。

1 个答案:

答案 0 :(得分:0)

您有一个包含其他数组的数组,因此保持简单并仅使用foreach循环,只要您希望从内部数组中获取某些内容,就可以启动另一个foreach循环来处理它。

使用循环处理的代码也应驻留在foreach内,而不在其后进行编码。

$response = curl_exec($cURL);

$result = json_decode($response, true);
curl_close($cURL);

foreach ($result as $value) {    

    print $value["registration"];
    print $value["make"];
    print $value["model"];
    print $value["fuelType"];
    print $value["primaryColour"];

    foreach ($value['motTests'] as $mot) {
        print $mot['expiryDate'];
        print $mot['odometerValue'];
    }
}