Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

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.

share|improve this question

marked as duplicate by deceze Jun 15 at 11:13

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

add comment

1 Answer

up vote 0 down vote accepted

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...
share|improve this answer
    
okay, so any suggested changes in my code? –  Aditya Bhatt Jun 15 at 10:17
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.