[英]Get key value from multidimensional array not working
I am trying to get a value from a multidimensional array by its name 'code'.我正在尝试通过名称“代码”从多维数组中获取一个值。 When I dump and die the first way it returns the correct value.
当我以第一种方式倾倒和死亡时,它会返回正确的值。 When I then want to use that in the code, it gives the error "Undefined index: code".
当我想在代码中使用它时,它会给出错误“未定义的索引:代码”。 I also used the array_column way, that dd an empty array.
我还使用了 array_column 方式,即 dd 一个空数组。
The code that should get the correct $code:应该得到正确 $code 的代码:
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: $house
转储:
array:30 [
id: ''
project: integer
city: ''
streetName: ''
houseNumber: ''
code: ''
fullStreet: ''
forms: array:1 [
0: integer
]
]
$code
dump $code
转储
$house['code']: "AB12-CD34-EF56-GH78"
array_column($house, 'code'): []
I would like to know the solution to this so that I can use the $code in the url to get the correct things back from the api.我想知道这个问题的解决方案,以便我可以使用 url 中的 $code 从 api 取回正确的东西。
You can use array_column on your entire array, not the sub-arrays.您可以在整个数组上使用 array_column,而不是子数组。
$houses =
[
[
'code' => '23',
'city' => 'Dublin'
],
[
'city' => 'Canberra'
],
[
'code' => '47',
'city' => 'Amsterdam'
]
];
var_export(array_column($houses, 'code'));
Output: Output:
array (
0 => '23',
1 => '47',
)
You could then do something along these lines.然后你可以按照这些思路做一些事情。
$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.
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.