[英]Comma separated list to an array of objects with values in php
I'm basically just trying to get from this: 我基本上只是试图从中得到:
$value="20, 40, 40"
$color="blue, green, orange"
To this: 对此:
var data = [ { value: 20, color:"blue" }, { value : 40, color : "green" }, { value : 40, color : "orange" }]
So I need to extract the value and color add put them item this array of objects. 所以我需要提取值和颜色添加把它们放在这个对象数组中。 I know how this could be done if only value needed to be set, not color as well using explode and foreach, but I have not idea how to do this needing both values.
我知道如果只需要设置值就可以做到这一点,而不是使用explode和foreach设置颜色,但我不知道如何做这个需要两个值。
Any ideas are much appreciated. 任何想法都非常感谢。
Thanks, 谢谢,
David 大卫
explode
两个数组,使用索引一次迭代两个,使用给定索引处的两个数组中的值来创建object / tuple / whatever,并在将它们存储在data
。
Do this 做这个
$value="20, 40, 40";
$color="blue, green, orange";
$explVal = explode(",", $value);
$explCol = explode(",", $color);
$arr = array();
for ($i=0; $i<count($explVal); $i++)
{
$arr[$i]['value'] = $explVal[$i];
$arr[$i]['color'] = $explCol[$i];
}
then do 然后做
$result = json_encode($arr);
Are there always going to be the same number of values in each, then? 那么每个值中是否总会有相同数量的值?
$value="20, 40, 40";
$color="blue, green, orange";
$values = explode(", ",$value);
$colors = explode(", ",$color);
$output = 'var data = [ ';
for($i = 0; $i < count($values) && $i < count($colors); $i++){
$output .= '{ value: '.$values[$i].', color:"'.$colors[$i].'" }, ';
}
$output = substr($output,0,-2);
$output .= ']';
echo $output;
Result is: 结果是:
var data = [ { value: 20, color:"blue" }, { value: 40, color:"green" }, { value: 40, color:"orange" }]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.