array_combine()期望参数1是数组,给定字符串

时间:2015-04-05 15:51:12

标签: php arrays

我正在尝试将两个数组与PHP的array_combine()函数组合在一起,并收到此错误:

  

array_combine()期望参数1为数组,字符串为

$ subject

var_dump显示了这一点:

array(
  (int) 0 => 'English',
  (int) 1 => 'Mathematics',
  (int) 2 => 'Biology',
  (int) 3 => 'Physics',
  (int) 4 => 'Chemistry'
) 

$ custom 的var_dump显示:

array(
  (int) 0 => array(
      'score' => '72',
      'grade' => 'B+',
      'points' => '10'
  ),
  (int) 1 => array(
      'score' => '99',
      'grade' => 'A',
      'points' => '12'
  ),
  (int) 2 => array(
      'score' => '77',
      'grade' => 'A-',
      'points' => '11'
  ),
  (int) 3 => array(
      'score' => '50',
      'grade' => 'C+',
      'points' => '7'
  ),
  (int) 4 => array(
      'score' => '66',
      'grade' => 'B+',
      'points' => '10'
  )
)

功能:

function score($received,$arr) {
    $keys = $received;
    $data_set = array_combine($keys,$arr);
    return $data_set;
}

这是我调用函数的地方:

$data_set = array_map(array($this->Scores,'score'),$subjects ,custom);

如果调试将所有变量显示为数组:为什么$ subject作为字符串出现在array_combine中?

修改

预期输出

array(
'English' => array(
    'score' => '72',
    'grade' => 'B+',
    'points' => '10'
),
'Mathematics' => array(
    'score' => '99',
    'grade' => 'A',
    'points' => '12'
),
'Biology' => array(
    'score' => '77',
    'grade' => 'A-',
    'points' => '11'
),
'Physica' => array(
    'score' => '50',
    'grade' => 'C+',
    'points' => '7'
),
'Chemistry' => array(
    'score' => '66',
    'grade' => 'B+',
    'points' => '10'
)
)

2 个答案:

答案 0 :(得分:1)

当您使用预期输出更新问题时,您不需要array_map()。就这样做:

$data_set = array_combine($subjects, $custom);

否则,您所做的就是遍历$subjects$custom的所有元素。

所以你做的就是每次迭代:

return array_combine("English", ["score" => "72", "grade" => "B+", "points" => "10"]);
return array_combine("Mathematics", ["score" => "99", "grade" => "A", "points" => "12"]);
//...

答案 1 :(得分:0)

简单地试试这个,不需要额外的array_map

$data_set = array_combine($subjects, $custom);