我有多个维度数组包含各种值,并希望根据用户输入将相应的数组或$profile
调出到HTML表单中。
我已经开始使用array_map
,array_filter
和封闭,但我对他们来说只是新手,所以我非常感谢您的代码解决方案旁边的解释,以帮助我学习。我知道有很多类似的问题,但我似乎无法理解它们。
<?php
$profileArray = array(
array( 'Name' => "Toby",
'Age' => 3,
'Gender' => "Male",
),
array( 'Name' => "Cassie",
'Age' => 3,
'Gender' => "Female",
),
array( 'Name' => "Lucy",
'Age' => 1,
'Gender' => "Female",
),
);
$profiles = $profileArray[1][2][3];
class profileFilter {
function get_profile_by_age ($profiles, $age){
return array_filter ($profiles, function($data) use ($age){
return $data->age === $age;
});
}
}
var_dump (get_profile_by_age ($profiles, 3));
当我在浏览器中尝试此操作时,我在var_dump
编辑:我修复了建议的语法错误,但仍然没有运气。我正确地调用了我的阵列吗?我觉得我也错过了一个步骤或语法。
答案 0 :(得分:1)
// meaningless line
// $profiles = $profileArray[1][2][3];
// i don't understand for what purpose you create a class,
// but if do, declare function as static
// or create an object and call it by obj->function
class profileFilter {
static function get_profile_by_age ($profile, $age){
return array_filter ($profile, function($data) use ($age){
// $data is arrray of arrays, there is no objects there
return $data['Age'] === $age;
});
}
}
var_dump (profileFilter::get_profile_by_age ($profileArray , 3));
// now it works
答案 1 :(得分:-1)
嗯,有几个错误。 (只是纠正语法错误)
<?php
$profileArray = array(
array(
'Name' => 'Toby', //here are the ' missing
'Age' => 3,
'Gender' => "Male",
),
...
我不知道你的数组中是否有像'Name'这样的类,但我假设你没有,所以这些名字也应该用引号括起来。
$profiles = $profileArray[1][2][3];
class profileFilter {
function get_profile_by_age ($profile, $age){
return array_filter ($profiles, function($data) use ($age){
return $data->age === $age;
});
}//here is one missing
}
var_dump(get_profile_by_age ($profiles, 3));