PHP - array_search appends keys with json_encode function parsing issue [duplicate]

微笑、不失礼 提交于 2019-12-13 08:18:15

问题


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.


回答1:


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...


来源:https://stackoverflow.com/questions/24228468/php-array-search-appends-keys-with-json-encode-function-parsing-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!