问题描述
我正在尝试将两个数组与PHP的 array_combine()
函数结合起来,但出现此错误:
I'm trying to combine two arrays with PHP's array_combine()
function and I receive this error:
$ subjects 的var_dump显示如下:
var_dump of $subjects shows this:
array(
(int) 0 => 'English',
(int) 1 => 'Mathematics',
(int) 2 => 'Biology',
(int) 3 => 'Physics',
(int) 4 => 'Chemistry'
)
$ custom 的var_dump显示以下内容:
var_dump of $custom show this:
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);
如果调试将所有变量都显示为数组:为什么$ subjects出现为array_combine的字符串?
if the debug shows all the variables as arrays: why is $subjects appearing as string to 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'
)
)
推荐答案
在使用预期的输出更新问题时,不需要 array_map()
.只需这样做:
As you updated your question with the expected output you don't need array_map()
. Just do this:
$data_set = array_combine($subjects, $custom);
否则,您所做的就是遍历 $ subjects
和 $ custom
的所有元素.
Otherwise what you did is loop through all elements of $subjects
and $custom
.
所以您要做的是每次迭代:
So what you did is this each iteration:
return array_combine("English", ["score" => "72", "grade" => "B+", "points" => "10"]);
return array_combine("Mathematics", ["score" => "99", "grade" => "A", "points" => "12"]);
//...
这篇关于array_combine()期望参数1为数组,给定字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!