php数组将值从一个数组添加到另一个数组

问题描述 投票:1回答:4

我有2个数组,都是从单独的mysql查询生成的,如下所示:

阵列1

[0] => Array
    (
        [value] => black
        [hex_colour] => #000000
    )

[1] => Array
    (
        [value] => blue
        [hex_colour] => #4e5f98
    )

[2] => Array
    (
        [value] => brown
        [hex_colour] => #a3775e
    )

阵列2

[0] => Array
    (
        [value] => black
        [count] => 122
    )

[1] => Array
    (
        [value] => blue
        [count] => 33
    )

[2] => Array
    (
        [value] => brown
        [count] => 5
    )

我的问题是如何将[count]添加到ARRAY 1,结果将是:

新ARRAY

[0] => Array
    (
        [value] => black
        [hex_colour] => #000000
        [count] => 122
    )

[1] => Array
    (
        [value] => blue
        [hex_colour] => #4e5f98
        [count] => 33
    )

[2] => Array
    (
        [value] => brown
        [hex_colour] => #a3775e
        [count] => 5

    )

我很抱歉,我没有尝试过的代码示例,但我使用了许多不同的搜索条件搜索了谷歌,但没有运气。任何帮助都会受到极大的欢迎。

php mysql arrays
4个回答
2
投票

我认为这是满足您的要求。

$arrayName1[0] = array(
        'value' => "black",
        'hex_colour' => "#000000",
    );
    $arrayName1[1] = array(
        'value' => "blue",
        'hex_colour' => "#4e5f98",
    );
    $arrayName1[2] = array(
        'value' => "brown",
        'hex_colour' => "#a3775e",
    );

    $arrayName2[0] = array(
        'value' => "black",
        'count' => "122",
    );
    $arrayName2[1] = array(
        'value' => "blue",
        'count' => "33",
    );
    $arrayName2[2] = array(
        'value' => "brown",
        'count' => "5",
    );

    foreach ($arrayName1 as $key => $row1) {
        foreach ($arrayName2 as $key => $row2) {
            if($row1['value'] == $row2['value'] ){
                $row1['count'] = $row2['count'];
                $data[] = $row1;
                break;
            }
        }
    }

$data中,您可以获得与问题中提到的相同的数组。如果您有任何疑问,请在下面评论。


4
投票
$data= Array(
    'value' => 'black',
   'hex_colour' => '#000000'
);
$data1= Array(
    'value' => 'black',
   'count' => '122'
);


print_r(array_merge($data1, $data));

2
投票
$count_array=[];

foreach($array2 as $count)
{
    $count_array[$count['value']]=$count['count'];
}
$final=[];
foreach($array1 as $value)
{
    $final=[
             "value"=>$value['value'],
             "hex_colour"=>$value['hex_colour'],
             "count"=>$count_array[$value['value']]
        ];
}

2
投票

您可以尝试以下代码 -

  $array1= array(
    'value' => 'black',
   'hex_colour' => '#000000'
);
$array2= array(
    'value' => 'black',
   'count' => '122'
);

$result = array_merge($array1, $array2);

print_r($result);

供参考http://php.net/manual/en/function.array-merge.php

© www.soinside.com 2019 - 2024. All rights reserved.