【问题标题】:PHP: Creating a output using user input, array_filter and closure for a 2d mixed arrayPHP:为二维混合数组使用用户输入、array_filter 和闭包创建输出
【发布时间】:2016-05-22 06:21:09
【问题描述】:

我有包含各种值的多维数组,并希望根据用户输入到 HTML 表单中来调出适当的数组或$profile

我已经开始使用 array_maparray_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 出现语法错误

编辑:我已经修复了建议的语法错误,但仍然没有运气。我正确调用我的数组吗?我觉得我也错过了一个步骤或语法。

【问题讨论】:

  • 确切的语法错误信息是什么?
  • 你错过了 profileFilter 类定义的右花括号
  • @rsz 解析错误:语法错误,意外的 'var_dump' (T_STRING),期望函数 (T_FUNCTION)
  • @rsz 在按照 RomanPerekhrest 的建议关闭该括号后,显示了一个新错误:致命错误:未捕获的错误:调用未定义的函数 get_profile_by_age() 并注意:未定义的偏移量
  • 您在var_dump 之前缺少} - 投票结束。

标签: php arrays filtering


【解决方案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

【讨论】:

  • 我使用 $profiles = $profileArray[1][2][3]; 稍后在此处调用它 static function get_profile_by_age ($profiles, $age) 您的代码有效,但您能更清楚地向我解释一下这部分吗?感谢您提供正确的代码!
  • 你需要阅读类和方法。或者不要考虑这个,只是删除课程并让function get_profile_by_age(... 没有课程。
  • Statment $profiles = $profileArray[1][2][3]; 尝试将变量 $profiles 设置为 3d 数组项的值。例如,如果`$profileArray = [ [], [[], [1,2,3,4]]]` 那么$profiles 将为4;
  • 如果你只想复制数组$profiles = $profileArray;就足够了。之后您可以致电get_profile_by_age ($profile , 3);
  • 不,没必要 声明和调用时函数的参数使用相同的名称。
【解决方案2】:

嗯,有几个错误。 (只是纠正语法错误)

<?php
$profileArray = array( 
array(  
      'Name' => 'Toby', //here are the ' missing
      'Age' => 3, 
      'Gender' => "Male",
     ),
...

我不知道您的数组中是否有像“名称”值这样的类,但我假设您没有,所以名称也应该用引号引起来。

$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));

【讨论】:

  • 我已经改变了它们,但仍然没有快乐。
猜你喜欢
  • 2022-01-10
  • 1970-01-01
  • 1970-01-01
  • 2016-12-20
  • 2021-12-07
  • 1970-01-01
  • 1970-01-01
  • 2019-03-18
  • 1970-01-01
相关资源
最近更新 更多