Получить значение ключа из многомерного массива не работает - PullRequest
0 голосов
/ 08 ноября 2019

Я пытаюсь получить значение из многомерного массива по имени «код». Когда я бросаю и умираю первым способом, он возвращает правильное значение. Когда я затем хочу использовать это в коде, он выдает ошибку «Неопределенный индекс: код». Я также использовал путь array_column, который dd пустой массив.

Код, который должен получить правильный код $:

foreach ($houses as $house) {
    $code = $house['code']; //Returns correct value in a dd, not in the code
    $code = array_column($house, 'code'); //Returns empty array in dd, later gives the error Array to string conversion in the file_get_contents
    $a = file_get_contents('some-url' . $code . '/surveys');
    $a = json_decode($a, true);

    $surveys = $a['surveys'];
    $completedSurveys = $a['surveysCompleted'];

    $done = 0;
    $ndone = 0;

    foreach ($completedSurveys as $complete) {
        if($complete) {
            $done++;
        } else if(!$complete) {
            $ndone++;
        } else {continue;}
    }
}

$house dump:

array:30 [
    id: ''
    project: integer
    city: ''
    streetName: ''
    houseNumber: ''
    code: ''
    fullStreet: ''
    forms: array:1 [
        0: integer
    ]
]

$code dump

$house['code']: "AB12-CD34-EF56-GH78"
array_column($house, 'code'): []

Мне бы хотелось узнать решение этой проблемы, чтобы я мог использовать $ code в URL, чтобы получить правильные данные из API.

1 Ответ

0 голосов
/ 08 ноября 2019

Вы можете использовать array_column для всего массива, а не для подмассивов.

$houses = 
[
    [
        'code' => '23',
        'city' => 'Dublin'
    ],
    [
        'city' => 'Canberra'
    ],
    [
        'code' => '47',
        'city' => 'Amsterdam'
    ]
];

var_export(array_column($houses, 'code'));

Вывод:

array (
  0 => '23',
  1 => '47',
)

Затем вы можете сделать что-то в этом духе.

$get_survey = function ($code) {
    if($response = file_get_contents("http://example.com/$code/surveys"))
        if($json = json_decode($response, true))
            return $json;
};

$completed = [];
foreach(array_column($houses, 'code') as $code) {
    if($survey = $get_survey($code)) {
        // survey count calculation.
    } else {
        $completed[$code] = null; // failure to get survey data.
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...