0

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.

Any ideas are much appreciated.

Thanks,

David

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks chandresh_cool that works great. Thanks to everyone else who replied as well.
Cheers David. Wish U Happy Coding :)
1

explode both arrays, use an index to iterate over both at once, using the values in both arrays at a given index to create the object/tuple/whatever, and as you make them store them in data.

Comments

0

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" }]

2 Comments

Don't build json by hand, use the function json_encode
That's a great function, but I didn't strictly know the asker needed JSON as it wasn't specified, though you can infer that from his example. At least he got some ideas. :P

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.