-1

Below is my JSON Result when I do not replace the order of channels as per timings:

"channels": [

{
    "id": "1",
    "name": "LBC دراما "
},
{
    "id": "2",
    "name": "KTV Arabe"
},
{
    "id": "3",
    "name": "KTV Plus"
}

]

Now, when I replace the array keys with values returned by array_search function, it brings the key with array response which is problem for me:

"channels": {

"0": {
    "id": "2",
    "name": "KTV Arabe"
},
"1": {
    "id": "1",
    "name": "LBC دراما "
},
"3": {
    "id": "3",
    "name": "KTV Plus"
}

}

code:

$newChannelsArr['channels'][array_search($channelsArr['channels'][$a]['id'], $data)] = ($channelsArr['channels'][$a]);

How can I overcome from keys getting appended in my json array?

My Code Snippet:

$data values:

 Array
    (
        [0] => 2
        [1] => 1
        [3] => 3
    )

$newChannelsArr = array();
    if(isset($data)){
        for($a = 0; $a < count($data); $a++){


            $kv = array_search($channelsArr['channels'][$a]['id'], $data);
            $newChannelsArr['channels'][(int)$kv] = ($channelsArr['channels'][$a]);

        }
    }

Solution:

Solution

ksort($newChannelsArr['channels']); // sort an array
$arr = array_map('array_values', $arr); // regenerate their keys 

It will be a quick patch.

Aditya P Bhatt
  • 21,431
  • 18
  • 85
  • 104

1 Answers1

0

No, because JSON array does not have keys. That's why when you added it, in second response you now got object, not array you had before and what you wanted to be your array keys become properties of object. You cannot access object as array. You must now access it as object:

$foo->property...
Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141