遍历多维数组-PHP

时间:2019-07-13 07:24:45

标签: php arrays json multidimensional-array

我正在尝试测试多维数组中的每个“凭证”,并被告知做到这一点的最佳方法是foreach循环。但是,我不确定如何使用$ key和$ value来访问凭证。

这是数组的样子:https://imgur.com/a/VXjJ4lG


foreach($allVouchers as $key => $value){
        $signIn = curl_init();
        $voucherURL = 'https://splash-static.ironwifi.com/radius_test.php?ip=' . $ip . '&backup_ip=' . $backupIP . '&auth_port=' . $port . '&secret=' . $secret . '&username=' . $allVouchers["_embedded"]["vouchers"][$key]['code'] . '&password=' . $allVouchers["_embedded"]["vouchers"][$key]['code'] . '&c=*cachebuster*&nas_ip=19.29.39.49';
        curl_setopt($signIn, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($signIn, CURLOPT_URL, $voucherURL);
        $access = curl_exec($signIn);
        curl_close($signIn);
        $accessArray = json_decode($access, true);
                print_r($accessArray);

    }

这是var_dump的输出:


    array(
9
) {
[0]=> array(
6
) {
[\"_links\"]=> array(
4
) {
[\"self\"]=> array(
1
) {
[\"href\"]=> string(
70
) \"https://europe-west2.ironwifi.com/api/67ec3855dc288c4f/vouchers?page=1\" }
[\"first\"]=> array(
1
) {
[\"href\"]=> string(
63
) \"https://europe-west2.ironwifi.com/api/67ec3855dc288c4f/vouchers\" }
[\"last\"]=> array(
1
) {
[\"href\"]=> string(
70
) \"https://europe-west2.ironwifi.com/api/67ec3855dc288c4f/vouchers?page=9\" }
[\"next\"]=> array(
1
) {
[\"href\"]=> string(
70
) \"https://europe-west2.ironwifi.com/api/67ec3855dc288c4f/vouchers?page=2\" } }
[\"_embedded\"]=> array(
1
) {
[\"vouchers\"]=> array(
25
) {
[0]=> array(
8
) {
[\"id\"]=> string(
32
) \"secret id\"
[\"code\"]=> string(
7
) \"mntvre7\"
[\"username\"]=> string(
7

1 个答案:

答案 0 :(得分:0)

在这里,我认为这是一个与您的等效的最小数据结构:

<?php
$data =
[
    [
        '_links' =>
        [
        ],
        '_embedded' =>
        [
            'vouchers' =>
            [
                [
                    'code' => 23
                ],
                [
                    'code' => 47
                ]
            ]
        ]
    ]
];

foreach($data as $item) {
    foreach($item['_embedded']['vouchers'] as $voucher) {
        echo $voucher['code'], "\n";
    }
}

输出:

23
47