0

I have an array:

$myAssocArray = array(
           ['fred','tyson',23],
           ['collins', 'white', 54],
           ['mary', 'frost', 46]
        );

When I json_encode the array:

$jsonString = json_encode($myAssocArray);
echo $jsonString;

I get:

[['fred','tyson',23],['collins', 'white', 54],['mary', 'frost', 46]]

But I would like the following result:

[{0:'fred',1:'tyson',2: 23},{0:'collins', 1:'white', 2: 54},{0:'mary', 1:'frost',2: 46}]
6
  • You can pass JSON_FORCE_OBJECT to the second argument of json_encode but that will not result in the exact value that you want. Commented Apr 7, 2018 at 22:59
  • Please don't use Markdown arbitrarily. Blockquotes (>) are for, well, quotes. They're not for emphasis. See stackoverflow.com/editing-help Commented Apr 7, 2018 at 23:05
  • Hi, I think that this means nothing in JSON "[{'fred','tyson',23},{'collins', 'white', 54},{'mary', 'frost', 46}]". Commented Apr 7, 2018 at 23:05
  • 1
    (a) Your PHP isn't an associative array, it's just an array of arrays. (b) The output you're showing is also an array of arrays, so it makes sense. (c) Your expected output isn't valid JSON. It's impossible to get that output from json_encode(). Commented Apr 7, 2018 at 23:06
  • It seems to have worked after I cast the sub arrays to objects Commented Apr 7, 2018 at 23:13

2 Answers 2

0

Found a solutiion, I had to cast the nested array to objects

(object) $myDynamicNestedArray;

PHP json_encode - JSON_FORCE_OBJECT mixed object and array output

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

2 Comments

Chris I understand the output i typed in the quesstion is not valid json (I was just free styling on the keyboard not checking syntax), but the problem is still valid if you change it to a valid json string
I just edited the final json output in the question. With regards to the answer. $dataArray->push((object)$data->all()); $dataArray->toJson(); ended up giving me the output I was expecting
0

Convert the array to an object (object)$array, something like:

function _json_encode($arr){
   return json_encode((object)$arr); 
}

$jsonString = _json_encode($myAssocArray);
print_r($jsonString);

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.