Home > Back-end >  PHP Array Keys always return zero
PHP Array Keys always return zero

Time:10-09

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"}

CodePudding user response:

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.

  • Related