0

I have an array

[0] => array(3) {
    ["id"] => string(1) "2"
    ["name"] => string(10) "Contractor"
    ["statuses"] => array(4) {
      [1] => array(3) {
        ["id"] => string(1) "1"
        ["name"] => string(3) "NEW"
        ["count"] => string(2) "32"
      }
      [3] => array(3) {
        ["id"] => string(1) "3"
        ["name"] => string(8) "RETURNED"
        ["count"] => string(2) "20"
      }
      [5] => array(3) {
        ["id"] => string(1) "5"
        ["name"] => string(6) "FAILED"
        ["count"] => string(2) "46"
      }
      [58] => array(3) {
        ["id"] => string(2) "58"
        ["name"] => string(6) "REVISE"
        ["count"] => string(3) "197"
      }
    }
  }

now when I convert into JSON it look like this

"items":[{"id":"2","name":"Contractor","statuses":{"1":{"id":"1","name":"NEW","count":"32"},"3":{"id":"3","name":"RETURNED","count":"20"},"5":{"id":"5","name":"FAILED","count":"46"},"58":{"id":"58","name":"REVISE","count":"197"}}}...

how to I remove the preceding 1, 3, 6 and 58 from array or JSON

I have tried array_values() but it is not converting the nested part of the array

4
  • so you basically need to unset statuses? Commented Apr 4, 2016 at 16:28
  • The documentation answers your question pretty well. Commented Apr 4, 2016 at 16:32
  • no i just want to remove that [1],[3],...[58] from nested array Commented Apr 4, 2016 at 16:43
  • 1
    try $array['statuses'] = array_values($array['statuses']) Commented Apr 4, 2016 at 16:47

1 Answer 1

2

how to i remove the preceding 1, 3, 6 and 58 from array or json

If you want json_encode() to return JSON array all the array keys must:

  • be numeric
  • be in sequence
  • the sequence must start from 0

For example:

$a = [1,2,3];
echo json_encode($a);

outputs desired

[1,2,3]

same with explicitly set indexes:

$a = [0=>1,2,3];

but

$a = [1=>1,2,3];

would output object:

{"1":1,"2":2,"3":3}

because sequence does not start from 0. Same for your case:

$a = [1,2,58=>3];

which produces

{"0":1,"1":2,"58":3}

because continuity of the key sequence is broken by index 58.

So depending on how you build your source array simply remove own keys with i.e. array_values():

$a = [1,2,58=>3];
echo json_encode(array_values($a)]);

would produce

[1,2,3]

so use array_values() on your $data['statuses'] and you are done.

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

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.