简体   繁体   English

如何合并两个数组并使用PHP合并值

[英]How to merge two arrays and concat the values with PHP

I'm looking for an easy solution to create a little function to merge two arrays with value concat (I'm using it to create html tag attribute): 我正在寻找一个简单的解决方案来创建一个小函数来合并两个具有值concat的数组(我正在使用它来创建html标签属性):

$default["class"] = "red";

$new["class"] = "green";
$new["style"] = "display:block"

The result: 结果:

$res["class"] = "red green";
$res["style"] = "display: block";

and one more option: if the $new is not an array, just concat with the $default["class"] (if this exist), and the other side: if the $default is a simple string, convert to array: $default["class"] = $default ; 还有一个选择:如果$new不是数组,只需与$default["class"] (如果存在)连接,另一边:如果$default是简单字符串,则转换为数组: $default["class"] = $default ;

I created a function but would like to use an easier, shorter way for that: 我创建了一个函数,但想使用一种更简单,更短的方法:

function attrMerge( $default, $new="" ){
    $res = array();

    if(!is_array($default)) {
        $res["class"] = $default;
    }
    else {
        $res = $default;
    }

    if( $new !== "" ){
        if(!is_array($new)) {
            if(isset($res["class"])){
                $res["class"].= " ".$new;
            }
        }
        else {
            foreach($new as $key=>$value) {
                if( isset($res[$key]) ) {
                    $res[$key].= " ".$value;
                }
                else {
                    $res[$key] = $value;
                }
            }
        }
    }

    return $res;
}

$a = attrMerge("red", array("class"=>"green", "style"=>"display: block;"));

I think this is the function that you need. 我认为这是您需要的功能。 I have initialised the css classes and styles as empty and in depends what you pass into the function then you get the relevant array 我已经将css类和样式初始化为空,并且取决于您传递给函数的内容,然后获得相关的数组

/**
* This function returns an array of classes and styles
*
* @param $default
* @param $new
* @return array
*/
function attrMerge($default=null, $new=nul)
{
    $result = array();
    $result['class'] = "";
    $result['style'] = "";

    // add default class if exists
    if (!empty($default) && is_string($default)) {
        // $default is string
        $result['class'] = $default;
    }
    if (!empty($default)
        && is_array($default)
    ) {
        if (array_key_exists('class', $default)
            && !empty($default['class'])
        ) {
           // $default['class'] exists and it's not empty
           $result['class'] = $default['class'];
        }
        if (array_key_exists('style', $default)
            && !empty($default['style'])
        ) {
           // $default['style'] exists and it's not empty
           $result['style'] = $default['style'];
        }
    }

    // add additional classes OR styles
    if (!empty($new)) {
        if(!is_array($new)) {
            $result['class'] = empty($result['class'])
                ? $new
                : $result['class'] . " " . $new;
        } else {
            foreach ($new as $key => $value) {
                if (isset($result[$key])) {
                    $result[$key] = empty($result[$key])
                        ? $value
                        : $result[$key] . " " . $value;
                } else {
                    $result[$key] = $value;
                }
            }
        }
    }

    return $result;
}

A way I believe suits your need, hopefully it's as adaptable and effecient as you were expecting. 我相信一种适合您需求的方式,希望它像您期望的那样适应性强和效率高。

$array1 = array(
'class' => 'class1',
'style' => 'display: none;'
);

$array2 = array(
    'class' => 'class2'
);

$arrayFinal = arrayMerge($array1, $array2);
var_dump($arrayFinal);

function arrayMerge($arr1, $arr2 = ''){
    // Array of attributes to be concatenated //
    $attrs = array('class');
    if(is_array($arr2)){
        foreach($attrs as $attr){
            if(isset($arr1[$attr]) && isset($arr2[$attr])){
            // Not using .= to allow for smart trim (meaning empty check etc isn't needed //
            $arr1[$attr] = trim($arr1[$attr] . ' ' . $arr2[$attr]);
            }
        }
    }else{
        $arr1['class'] = trim($arr1['class'] . ' ' . $arr2);
    }

    return $arr1;
}
$def = ['class' => 'red'];
$new = ['class' => 'green', 'style' => 'style'];

function to_array($in) {
    return is_array($in) ? $in : ['class' => $in];
}

$def = to_array($def);
$new = to_array($new);

$res = $def;
array_walk($new, function ($val, $key) use (&$res) {
   $res[$key] = trim(@$res[$key] . ' ' . $val);
});

var_dump($res);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM