dongshenyu4638 2014-12-10 20:52
浏览 317
已采纳

在PHP中为多个数组分配相同的key => value对

I'm trying to write a function that assigns the same key => value pair to multiple arrays. But the assignment doesn't occur.

<?php

// for debugging
error_reporting(E_ALL);

// arrays is an array of reference arrays
function assignKeyValueToArrays($arrays, $key, $value) {

    if(!is_scalar($key) || !is_array($arrays)) {
        return false;
    }

    foreach($arrays as $array) {
        if(!is_array($array)) return false;
        echo "setting $key to $value";
        $array[$key] = $value;
    }

}

$s = array();
$t = array();

assignKeyValueToArrays(array(&$s, &$t), "a", "blahblah");

// should print array(1) {"a" => "blahblah"} but both print array(0) {}
var_dump($s);
var_dump($t);

?>

The context for this is that I have a script which is doing database queries and assigns keys to both a temporary $queryParams array and also a $jsonResponse array. I could just do two assignments but I wanted a more general solution that could handle more arrays.

  • 写回答

1条回答 默认 最新

  • doushi9780 2014-12-10 20:55
    关注

    You should pass $array to the foreach loop by reference too, like &$array.

    Checkout this Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置