dongsha7215 2013-12-01 17:09
浏览 44
已采纳

如何在PHP中分配名称而不是“0”$ key?

i am working on a php code to display d3js histogram,

// Coerce types.
bins.forEach(function(bin) {
bin.Income = +bin.Income;
bin.People = +bin.People;
});

// Normalize each bin to so that height = quantity/width;
// see http://en.wikipedia.org/wiki/Histogram#Examples
for (var i = 1, n = bins.length, bin; i < n; i++) {
bin = bins[i];
bin.offset = bins[i - 1].Income;
bin.width = bin.Income - bin.offset;
bin.height = bin.People / bin.width;
}

for reference, http://bl.ocks.org/mbostock/1624660

my data, instead of "Income" and "people" has "bs" and "cs". in the sample output the format in which the data comes is [object Array] i made my data in the similar way. in the above code, where income and people called, are from the $key. for me, it returns the following output.

Array ( [0] => {"0":"26.5","1":"80"} [1] => {"0":" 27","1":" 222"} 
[2] => {"0":"27.5","1":" 303"} 
[3] => {"0":" 28","1":" 408"} 
[4] => {"0":" 28.5","1":" 276"} 
[5] => {"0":" 29","1":" 151"} 
[6] => {"0":" 29.5","1":null} ) 

this was got from a simple foreach loop,

$object = new stdClass();
foreach ($map[$l] as $key => $value)
{
$object->$key = $value;
}
print_r($object);

by default, this $key is assigning "0" and "1" to each object itself. i want to call these objects using '$key' variable in some other part of my code. since it is "0" and "1", i am unable to call it. is there any way to assign the names "bs" to "0" and "cs" to "1" in the output array so that it displays,

Array ( [0] => {"bs":"26.5","cs":"80"} [1] => {"bs":" 27","cs":" 222"} 
[2] => {"bs":"27.5","cs":" 303"} 
[3] => {"bs":" 28","cs":" 408"} 
[4] => {"bs":" 28.5","cs":" 276"} 
[5] => {"bs":" 29","cs":" 151"} 
[6] => {"bs":" 29.5","cs":null} ) 

thanks in advance.

  • 写回答

1条回答 默认 最新

  • dongzhang5006 2013-12-01 17:14
    关注
    $object = new stdClass();
    foreach ($map[$l] as $key => $value)
    {
        if($key == 0)
            $object -> breaks = $value;
        elseif($key == 1)
            $object -> counts = $value;
    
    }
    print_r($object);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥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,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题