0

I can’t seem to get the result I need. Here is the array as it is provided by the sql query:

Array (
 [0] => Array ( 
     [id] => 7
     [description] => Accepted )
 [1] => Array ( 
     [id] => 8
     [description] => Declined )
 [2] => Array (
     [id] => 11 
     [description] => Deferred ) 
     )

Here is the format for how I need to have it foreach of the objects listed above:

['7'][‘7’] = “Accepted”;
['7'][‘8’] = “Declined ”;
['7'][‘11’] = “Deferred”;

...where the first array[‘7’] is an added value and needed for each object.

Seems easy enough, but the foreach statements I created return an error “cannot use scalar value as an array”

0

1 Answer 1

2
$rows = /*Your Data above*/
$data = array('7'=>array());
foreach($rows as $row)
    $data['7'][$row['id']] = $row['description'];

$jsonData = json_encode($data);

Might get 'er done

Sign up to request clarification or add additional context in comments.

5 Comments

Close, but not quite: {"7":{"7":"Accepted","8":"Declined","11":"Deferred"}}
That looks correct to me. You wont get it showing up as {{"7":{"7":"Accepted"}}, {"7":{"8":"Declined"}}, {"7":{"11":"Deferred, but accepted"}}} because the index 7 is common among the elements. the '7' index will only showup once when json_encoded
Gotcha. You're right. I was just contemplating that very thing. Thanks, man... :)
Sorry for the follow up, I'll open a new question if needed; but now when I array_merge($rowsA, $rowsB, and $rowsC) (not provided in the above example) with the same format you provided, I lose the leading array (in my case '7', '6', and '5'). Does array_merge not take that into account?
array_merge() flattens an array. duh. Sorry.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.