如何使用php匹配,合并和创建一个新数组

时间:2018-01-09 10:50:38

标签: php arrays

这对我来说是新的(并且数组不是我的那种东西),但不确定这是否可行,因为我在网上找不到任何示例但我有2个数据数组,这些数组包含一个名为&的值#39; slug',必须合并/组合(类别/产品)。这些slu is需要与名为'' language'这样我们就可以使用这些新值构建一个新数组。

//第一个数组:

Array(
[0] => Array
    (
        [category_id] => 5
        [attribute] => slug
        [language] => de
        [translation] => blanko
    )

[1] => Array
    (
        [category_id] => 5
        [attribute] => slug
        [language] => en
        [translation] => white
    )

[2] => Array
    (
        [category_id] => 5
        [attribute] => slug
        [language] => es
        [translation] => blanco
    )

[3] => Array
    (
        [category_id] => 5
        [attribute] => slug
        [language] => fr
        [translation] => vierges
    )

[4] => Array
    (
        [category_id] => 5
        [attribute] => slug
        [language] => it
        [translation] => bianche
    )
)

//第二个数组:

Array(
[0] => Array
    (
        [product_id] => 5
        [attribute] => slug
        [language] => de
        [translation] => ettiketten-xxx
    )

[1] => Array
    (
        [product_id] => 5
        [attribute] => slug
        [language] => en
        [translation] => labels-xxxx
    )

[2] => Array
    (
        [product_id] => 5
        [attribute] => slug
        [language] => es
        [translation] => etiquetas-xxxx
    )

[3] => Array
    (
        [product_id] => 5
        [attribute] => slug
        [language] => fr
        [translation] => etiquettes-xxx
    )

[4] => Array
    (
        [product_id] => 5
        [attribute] => slug
        [language] => it
        [translation] => etichette-xxxx
    )
)

我想创建一个像

这样的新数组
array(
   'de' => 'blanko/ettiketten-xxx',
   'fr' => 'vierges/etiquettes-xxx'
    // and so on
)

1 个答案:

答案 0 :(得分:0)

这是一个简单的例子,说明如何迭代这些并编译具有所需值的第三个数组:

$result = array();

foreach ($categories as $category) {
    foreach ($products as $product){
        if ($category['language'] == $product['language']){
            $translationString = $category['translation']."/".$product['translation'];
            $result[$category['language']] = $translationString;
        }
    }
}

echo print_r($result);

这将为您提供如下数组:

Array(
   'de' => 'blanko/ettiketten-xxx',
   'en' => 'white/labels-xxxx',
   'es' => 'blanco/etiquetas-xxxx,
   'fr' => 'vierges/etiquettes-xxx'
)

你赢得了任何积分的风格,但是使用array_maparray_walk可能有更好的方法来做到这一点所以如果你需要进行扩展可能需要考虑一下出