0

I have an this array (i show it here as a json..):

[
{
"icon1_name":"Home Address A",
"icon2_name":"Home Address B",
"icon3_name":"Home addressC",
},
{
"icon1_name":"OfficeA",
"icon2_name":"OfficeB",
"icon3_name":"OfficeC",
}

]

I'm trying to add an array in the middle (between home address and office). This what i tried to do:

array_splice( $myArray, 1, 0, $arrayToInsert );

But i get the result with numbers:

    {
    "1":{
    "icon1_name":"OfficeA",
    "icon2_name":"OfficeB",
    "icon3_name":"OfficeC",
    "
    },
  "2":{
    "icon1_name":"PhoneA",
    "icon2_name":"PhoneB",
    "icon3_name":"PhoneC",
    "
    },
    "3":{
    "icon1_name":"FaxA",
    "icon2_name":"FaxB",
    "icon3_name":"FaxC",
    }}

How can i do this merge without getting it numbered? Thats mean, keep the original json format.

10
  • What do you mean without getting it numbered? Commented Jul 1, 2014 at 19:14
  • Look at the second JSON. its not the same. Its has array numbers: "1","2","3"... Commented Jul 1, 2014 at 19:15
  • 1
    You could call array_values on the array in php which would reset the numbers back to starting with 0 and when converted to json make the outter array an array, not an object. Commented Jul 1, 2014 at 19:17
  • @jonathankuhn nice, you should make it an answer Commented Jul 1, 2014 at 19:20
  • @nl-x I could, but it really isn't ideal. The real answer should be how to not have the problem in the first place. But it does work. I just don't have the time (at work) to debug and fix it so I generally just throw up quick comments with quick fixes. Commented Jul 1, 2014 at 19:21

1 Answer 1

1

The array_splice code you posted works fine with the JSON strings decoded as here:

$myArray = json_decode('[
    {
        "icon1_name":"Home Address A",
        "icon2_name":"Home Address B",
        "icon3_name":"Home addressC"
    },
    {
        "icon1_name":"OfficeA",
        "icon2_name":"OfficeB",
        "icon3_name":"OfficeC"
    }
]');

$arrayToInsert = json_decode('[
    {
        "icon1_name":"PhoneA",
        "icon2_name":"PhoneB",
        "icon3_name":"PhoneC"
    }
]');

array_splice( $myArray, 1, 0, $arrayToInsert );

print_r( json_encode($myArray) );

Output:

[
  {
    "icon1_name":"Home Address A",
    "icon2_name":"Home Address B",
    "icon3_name":"Home addressC"
  },
  {
    "icon1_name":"PhoneA",
    "icon2_name":"PhoneB",
    "icon3_name":"PhoneC"
  },
  {
    "icon1_name":"OfficeA",
    "icon2_name":"OfficeB",
    "icon3_name":"OfficeC"
  }
]

Are the JSON strings you're decoding into PHP arrays different than these?

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.