0

I Have Data, from database example $data = array('12201700013','12201700014','12201700015')

I want use DOCS_NUM to keys and values,

My codes

$return = array('' => '- Choose Document Number -');
if ($data) {
    $dok = array();
    foreach ($data as $key => $value) {
        $dok[$value->DOCS_NUM] = $value->DOCS_NUM;
    }
    $return = array_merge($return, $dok);
} 
echo json_encode($return);

the json return always {"":"- Choose Document Number -","0":"12201700013"}

i tried change to $dok[(String)$value->DOCS_NUM] = $value->DOCS_NUM; and $dok[strval($value->DOCS_NUM)] = $value->DOCS_NUM; but the return still same.

i want the return {"":"- Choose Document Number -","12201700013":"12201700013"}

1 Answer 1

1

You can directly add key=>value pair to $return array with foreach loop Try doing this

foreach ($data as $key => $value) {
    $return[$value->DOCS_NUM] = $value->DOCS_NUM;
}

and comment out // $return = array_merge($return, $dok); this line, it should do the trick for you.

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

3 Comments

it solved my problem too, can u tell me why i got that error?, and this code solve my problem?
Because array_merge only takes the value part of $dok array and adds it to index 0 to $return array. So resultant $return array becomes Array ( [] => - Choose Document Number - [0] => 12201700013 ) and json_encode return 0 for the second element key :)
remember when using array_merge if the key exist in 1st from from 2nd array, results value is taken from 2nd array, but if key in 1st array does not not exist, new value is insert in result

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.