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

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

Without foreach, how can I turn an array like this

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


        
相关标签:
11条回答
  • There is also var_export and print_r more commonly known for printing debug output but both functions can take an optional argument to return a string instead.

    Using the example from the question as data.

    $array = ["item1"=>"object1", "item2"=>"object2","item-n"=>"object-n"];
    

    Using print_r to turn the array into a string

    This will output a human readable representation of the variable.

    $string = print_r($array, true);
    echo $string;
    

    Will output:

    Array
    (
        [item1] => object1
        [item2] => object2
        [item-n] => object-n
    )
    

    Using var_export to turn the array into a string

    Which will output a php string representation of the variable.

    $string = var_export($array, true);
    echo $string;
    

    Will output:

    array (
      'item1' => 'object1',
      'item2' => 'object2',
      'item-n' => 'object-n',
    )
    

    Because it is valid php we can evaluate it.

    eval('$array2 = ' . var_export($array, true) . ';');
    var_dump($array2 === $array);
    

    Outputs:

    bool(true)
    
    0 讨论(0)
  • 2020-12-04 07:54

    For debugging purposes. Recursive write an array of nested arrays to a string. Used foreach. Function stores National Language characters.

    function q($input)
    {
        $glue = ', ';
        $function = function ($v, $k) use (&$function, $glue) {
            if (is_array($v)) {
                $arr = [];
                foreach ($v as $key => $value) {
                    $arr[] = $function($value, $key);
                }
                $result = "{" . implode($glue, $arr) . "}";
            } else {
                $result = sprintf("%s=\"%s\"", $k, var_export($v, true));
            }
            return $result;
        };
        return implode($glue, array_map($function, $input, array_keys($input))) . "\n";
    }
    
    0 讨论(0)
  • 2020-12-04 07:55

    For create mysql where conditions from array

    $sWheres = array('item1'  => 'object1',
                     'item2'  => 'object2',
                     'item3'  => 1,
                     'item4'  => array(4,5),
                     'item5'  => array('object3','object4'));
    $sWhere = '';
    if(!empty($sWheres)){
        $sWhereConditions = array();
        foreach ($sWheres as $key => $value){
            if(!empty($value)){
                if(is_array($value)){
                    $value = array_filter($value); // For remove blank values from array
                    if(!empty($value)){
                        array_walk($value, function(&$item){ $item = sprintf("'%s'", $item); }); // For make value string type 'string'
                        $sWhereConditions[] = sprintf("%s in (%s)", $key, implode(', ', $value));
                    }
                }else{
                    $sWhereConditions[] = sprintf("%s='%s'", $key, $value);
                }
            }
        }
        if(!empty($sWhereConditions)){
            $sWhere .= "(".implode(' AND ', $sWhereConditions).")";
        }
    }
    echo $sWhere;  // (item1='object1' AND item2='object2' AND item3='1' AND item4 in ('4', '5') AND item5 in ('object3', 'object4'))
    
    0 讨论(0)
  • 2020-12-04 07:57

    I would use serialize() or json_encode().

    While it won't give your the exact result string you want, it would be much easier to encode/store/retrieve/decode later on.

    0 讨论(0)
  • 2020-12-04 08:00

    You could use http_build_query, like this:

    <?php
      $a=array("item1"=>"object1", "item2"=>"object2");
      echo http_build_query($a,'',', ');
    ?>
    

    Output:

    item1=object1, item2=object2 
    

    Demo

    0 讨论(0)
  • 2020-12-04 08:00

    Here is a simple example, using class:

    $input = array(
        'element1'  => 'value1',
        'element2'  => 'value2',
        'element3' =>  'value3'
    );
    
    echo FlatData::flatArray($input,', ', '=');
    
    class FlatData
    {
    
        public static function flatArray(array $input = array(), $separator_elements = ', ', $separator = ': ')
        {
            $output = implode($separator_elements, array_map(
                function ($v, $k, $s) {
                    return sprintf("%s{$s}%s", $k, $v);
                },
                $input,
                array_keys($input),
                array_fill(0, count($input), $separator)
            ));
          return $output;
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题