How to implode array with key and value without foreach in PHP

后端 未结 11 1399
悲&欢浪女
悲&欢浪女 2020-12-04 07:20

Without foreach, how can I turn an array like this

array(\"item1\"=>\"object1\", \"item2\"=>\"object2\",.......\"item-n\"=>\"objec         


        
11条回答
  •  一整个雨季
    2020-12-04 08:07

    Change

    -    return substr($result, (-1 * strlen($glue)));
    +    return substr($result, 0, -1 * strlen($glue));
    

    if you want to resive the entire String without the last $glue

    function key_implode(&$array, $glue) {
        $result = "";
        foreach ($array as $key => $value) {
            $result .= $key . "=" . $value . $glue;
        }
        return substr($result, (-1 * strlen($glue)));
    }
    

    And the usage:

    $str = key_implode($yourArray, ",");
    

提交回复
热议问题