drn9573 2017-07-18 13:36
浏览 43
已采纳

PHP填充关联数组的数组

I'm looping through some results list that contains information about fruit and who has picked.

Each iteration contains a single fruit and a single person who picked it.

foreach($Jobs as $key => $val) {

//set values
$fruit = $val->FruitName;
$picker = $val->Picker->ForeName;

//build my array here
$myArray[$val->FruitName] = $val->Picker->ForeName;

}

I'm trying to build up an associative array (using fruit names) that holds an array of the picker names, like so;

$myArray = array (
"apple" => array ("Jon","Jo","Dave"),
"pear" => array ("Ben"),
"plumb" => array ("Jane"),
"melon" => array ("Jon","Jo","Dave","Sarah"),
);

The way I'm currently attempting this simply overwrites the existing array of picker names.

  • 写回答

1条回答 默认 最新

  • dseax40600 2017-07-18 13:41
    关注
        foreach($Jobs as $key => $val) {
    
            //set values
            $fruit = $val->FruitName;
            $picker = $val->Picker->ForeName;
    
            //build my array here
            $myArray[$val->FruitName][] = $val->Picker->ForeName;
        }
    

    Using your example you need to add the [] to the build array line. This is so the names are added to the array rather than overwriting the value.

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

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?