2

I am trying to create a quick object for working with a graph I am making.

This is what the output looks like:

[
  ['Firefox',   45.0],
  ['IE',       26.8],
  ['Safari',    8.5],
  ['Opera',     6.2],
  ['Others',   0.7]
]

My code / loop that I need to use to create this data:

$series = Array();
foreach($segmentData->segment as $segment){ 

    echo $segment->segmentName . ' has ' . $segment->total . '<br />';
    //Need to create the data here

}
2
  • Why not use json_encode? Commented Jun 6, 2014 at 15:14
  • Just append a simple two-value array to your $series array? Commented Jun 6, 2014 at 15:15

2 Answers 2

2

Since the reference array provided is not an object/non-associative you cannot create keys in PHP then json_encode it. The reference array provided simply needs a 2 element array for each segment. Simply create the data using a PHP non-associated array. Then json_encode the data. This should match exactly the reference array you provided.

$output = array();
foreach($segmentData->segment as $segment){ 
    array_push($output, array($segment->segmentName, $segment->total));
}
header("Content-type: application/json");
echo json_encode($output);
Sign up to request clarification or add additional context in comments.

6 Comments

This didn't create the output that I listed :/
[[{"0":"SSP II"},{"0":"3"}],[{"0":"Limitations"},{"0":"2"}],[{"0":"Disputes"},{"0":"2"}],[{"0":"PSS"},{"0":"4"}],[{"0":"Debit Card"},{"0":"5"}]]
Odd... this means your variables you provided are objects themselves and not simply text/numbers. what does var_dump($segment->segmentName) and var_dump($segment->total) output?
array_push($output, array((string)$segment->segmentName, (string)$segment->total)); this fixed it :)
Is there a way to not include quotes around the numeric value though ? [["SSP II","3"],["Limitations","2"],["Disputes","2"],["PSS","4"],["Debit Card","5"]] the quotes around the numbers throw it off
|
1

to create json object add the values to an array in loop and then using json_enode do like below

foreach($segmentData->segment as $segment){ 

        $final[$segment->segmentName]=$segment->total;
    }

    $final = json_encode($final);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.