1

Is it possible to create something like this in PHP? I am trying to get around the automatic sorting of numeric indexes when I pick up the JSON object.

Or is it better to use a alphanumeric key to get around this problem?

This:

[
   {'key': 5, 'val': 2},
   {'key': 2, 'val': 2},
   {'key': 1, 'val': 1}
]

Instead of something like this:

[
  {1: {'key': 5, 'val': 2}},
  {2: {'key': 2, 'val': 2}},
  {3: {'key': 1, 'val': 1}}
]
0

1 Answer 1

1

You said it - JSON! Try using json_encode

$arr = [
    ["key"=>5, "val"=>2],
    ["key"=>2, "val"=>2],
    ["key"=>1, "val"=>1]
];

print_r( $arr ); // Numerically indexed array...
// Array ( [0] => Array ( [key] => 5 [val] => 2 ) [1] => Array ( [key] => 2 [val] => 2 ) [2] => Array ( [key] => 1 [val] => 1 ) ) 

$json = json_encode( $arr );
echo $json; // [{"key":5,"val":2},{"key":2,"val":2},{"key":1,"val":1}]



// Example: wrap array into Object with property name:
$obj["items"] = $arr;
$json = json_encode( $obj );
echo $json; // {"items":[{"key":5,"val":2},{"key":2,"val":2},{"key":1,"val":1}]}
Sign up to request clarification or add additional context in comments.

4 Comments

I was overthinking this way too much. But is there also a way to make the outer array an object? I tried JSON_FORCE_OBJECT but that inserts numeric keys into the JSON string.
@HåkanKA I don't see why you should bother at all. Indexes are only helpful while being in PHP world. At the point you need to send your JSON, simply json_encode it.
@HåkanKA if you want an outer "object" than do: $outer = ["items"=> $arr ]; Again everything will be indexed (who cares), unless you finally convert it to JSON: json_encode($outer);
I think is the Chrome inspector response preview and the Redux DevTools that have been messing up my debugging of this problem. They seem to add the index numbers even if they are not in the actual JSON string. So I probably had this solution at some point, but assumed it wasn't working.

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.