我有包含各种值的多维数组,并希望根据用户输入到 HTML 表单中的内容来调出适当的数组或
$profile
。
我已经开始使用
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
上收到语法错误
编辑:我已经修复了建议的语法错误,但仍然没有运气。我正确调用我的数组吗?我觉得我也缺少一个步骤或语法。
// 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
嗯,有几个错误。 (只是纠正语法错误)
<?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));