1

我正在使用 php 5.2.10 我想在数组上执行 array_map 并且我创建了一个用于数组映射的函数

function get_result(){
    $result = mysql_query("Select * from table");
    while($cr = mysql_fetch_array($result)){
        $b = array_map(`calc`,$cr);
        $rr_id = $cr['batch_id'].$cr['seq_id'];
  $mqrrid = '999'.$rr_id;
  $question_id = $cr['question_id'];
        foreach ($b as $k => $v){
            if(preg_match('{^Item \d+$}',$k)){
                $new_insert[] = array(
                    'r_id'=>$mqrrid,
                    'q_id' =>$q_id,
                    'c_id' =>$k,
                    'rank'=>$v
                );
            }
        }
    }
}   

function calc($n){
    foreach($n as $m=> &$x) {
        if (preg_match('{^Item \d+$}', $m)) {
            if($x == null){
                $x = $x;
            }else {
                $x = $x - 1;
            }
        }
    }   
    return $n;
}

我不知道为什么我不能调用函数calc......array_map我无法弄清楚原因......有人可以帮助我吗?

原始数组:(实际上array_map(calc,$cr)之后的输出与以下相同)

array(23) {
["batch_id"]=>
string(1) "1"
["seq_id"]=>
string(1) "1"
["question_id"]=>
string(4) "2086"
["Item 1"]=>
string(1) "1"
["Item 2"]=>
string(1) "2"
["Item 3"]=>
string(1) "3"
["Item 4"]=>
string(1) "4"
["Item 5"]=>
string(1) "5"
["Item 6"]=>
NULL

我需要的是:(将第 1 项到第 6 项的值减去 1,如果它的 null 就离开它~)

array(23) {
["batch_id"]=>
string(1) "1"
["seq_id"]=>
string(1) "1"
["q_id"]=>
string(4) "2086"
["Item 1"]=>
string(1) "0"
["Item 2"]=>
string(1) "1"
["Item 3"]=>
string(1) "2"
["Item 4"]=>
string(1) "3"
["Item 5"]=>
string(1) "4"
["Item 6"]=>
NULL

最后,结果会变成这样:(以Item 1和Item 6为例)

 array(4) {
["r_id"]=>
string(5) "99911"
["q_id"]=>
string(4) "2086"
["c_id"]=>
string(6) "Item 1"
["rank"]=>
string(1) "0"
}
array(4) {
["r_id"]=>
string(5) "99916"
["q_id"]=>
string(4) "2086"
["c_id"]=>
string(6) "Item 6"
["rank"]=>
string(4) NULL
}
4

2 回答 2

3

calc should be global, otherwise it cannot be found. Also, you should pass a string (no ` but rather enclose in ' or ").

Additionally, in general (if you used PHP 5.3), it is better to pass a function reference to the array_map function, instead of a string:

$func = function calc() { ... }
array_map($func, $cr);
于 2013-05-14T09:26:25.143 回答
1

我认为您不必为array_map.

function get_result($link_identifier = NULL) {
    $result = mysql_query('Select * from table', $link_identifier);
    $new = array();
    while ($rows = mysql_fetch_assoc($result)) {
        $r_id = '999' . $rows['batch_id'] . $rows['seq_id'];
        foreach ($rows as $k => $v) {
            if ($v !== null && preg_match('@^Item \\d+$@', $k)) {
                $v = (string)((int)$v + 1);
            }
            $new[] = array(
                'r_id' => $r_id,
                'q_id' => $rows['question_id'],
                'c_id' => $k,
                'rank' => $v,
            );
        }
    }
    return $new;
}
于 2013-05-14T09:37:07.603 回答