合并相同键下的值

时间:2017-08-03 01:08:12

标签: php arrays

我有一个这样的数组:

[Unicode.Scalar: State]

我需要把它变成这个:

Array ( 
    [Example] => Array ( 
        [0] => 1,2,3,4 
        [1] => 2,4,5,6,7
    ) 
)

所以只需一个密钥,并删除重复项。

编辑 - 这是我正在使用的实际代码。

我在WordPress中有一个设置列表,用户可以在其中选择他们的Google字体,以及使用该字体的变体。

我有一系列设置,我正在循环:

Array ( 
    [Example] => Array ( 
        [0] => 1,2,3,4,5,6,7
    ) 
)

现在使用这些值,我可以构建我的URL以从Google请求字体:

$options = array(
    'first_option',
    'second_option',
);

$font_families = array();
$font_variants = array();

foreach ( $options as $key ) {
    $value = get_theme_mod( $key );

    if ( ! in_array( $value, $font_families ) ) {
        $font_families[$value] = $value;
    }

    if ( ! isset( $font_variants[$value] ) ) {
        $font_variants[$value] = array();
    }

    $font_variants[$value] = get_theme_mod( $key . '_variant' );
}

print_r( $font_families );
// Array ( [Open+Sans] => Open+Sans [Amiri] => Amiri )

print_r( $font_variants );
// Array ( [Open+Sans] => Array ( [0] => 300,regular,italic,700 [1] => 300italic,regular,italic,600,600italic,700,700italic,800,800italic ) [Amiri] => Array ( [0] => regular,italic,700,700italic ) )
// The above is where the issue comes in, I need to merge [0] and [1] inside the same array.

问题出在Open Sans调用中 - 当我们只需要调用它们一次时,我们会调用两次变体。

3 个答案:

答案 0 :(得分:2)

您需要MSDNarray_merge

# pull images
docker pull wurstmeister/zookeeper 
docker pull wurstmeister/kafka

# run kafka & zookepper
docker run -d --name zookeeper -p 2181 -t wurstmeister/zookeeper  
docker run --name kafka -e HOST_IP=localhost -e KAFKA_ADVERTISED_PORT=9092 -e KAFKA_BROKER_ID=1 -e ZK=zk -p 9092:9092 --link zookeeper:zk -t wurstmeister/kafka  

# enter container
docker exec -it ${CONTAINER ID} /bin/bash  
cd opt/kafka_2.11-0.10.1.1/ 

# make a tpoic
bin/kafka-topics.sh --create --zookeeper zookeeper:2181 --replication-factor 1 --partitions 1 --topic mykafka 

# start a producer in terminal-1
bin/kafka-console-producer.sh --broker-list localhost:9092 --topic mykafka 

# start another terminal-2 and start a consumer
bin/kafka-console-consumer.sh --zookeeper zookeeper:2181 --topic mykafka --from-beginning 

答案 1 :(得分:0)

您正在寻找array_merge(),这会删除重复的密钥。

由于您的示例似乎使用字符串来存储您的数字,您还可以在逗号上查找 explode()

<?php

$string1 = "1, 2, 3, 4";
$string2 = "2, 4, 5, 6, 7";

$array1 = explode(",", $string1);
$array2 = explode(",", $string2);

print_r(array_merge($array1, $array2));

/* Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 2 [5] => 4 [6] => 5 [7] => 6 [8] => 7 ) */

?>

希望这有帮助! :)

答案 2 :(得分:0)

SORT_REGULAR方式很适合合并和删除重复项。您也可以尝试这种方式,请参阅此处的演示https://eval.in/840895

$array =[ 
    'Example' => [ 
        [1,2,3,4], 
        [2,4,5,6,7]
    ]
];

$result['Example'][0] = implode(',',array_unique(array_merge(... $array['Example'])));
print '<pre>';
print_r($result );
print '</pre>';
相关问题