将键指定给数组值

时间:2017-02-11 17:19:55

标签: php arrays key associative-array

我有一个从堆栈溢出中获得的函数: -

function testFunction($a, $b) {
    $map = array();
    foreach($a as $name => $value){
        if(!isset($b[$name]) || $b[$name] != $value) {
            $map[$value] = 1;
        }
    }
    return array_keys($map);
}

$array1 = array("Peter"=>"35", "Ben"=>"21", "Joe"=>"43");
$array2 = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"57");

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

这是我得到的结果:

Array ( [0] => 37 [1] => 57 )

因为第二个数组中的37与第一个数组中的21不同...而57与第43个不同。

我的问题是:如何为值添加键?例如,我想要这个:

Array ("Ben"=>"37", "Joe"=>"57");

2 个答案:

答案 0 :(得分:1)

你可以这样做: -

DECLARE @boat_id VARCHAR(50);
SET @boat_id = (SELECT Boats.sails.value('local-name(/sails[1]/*[1])','nvarchar(50)') 
                FROM Boats 
                WHERE boat_id = 88 
                  AND Boats.sails.value('(/sails/*/sailinfo)[1]', 'nvarchar(50)') = 'A2');

DECLARE @record_id varchar(50);
SET @record_id = (SELECT Records.sails.value('local-name(/sails[1]/*[1])', 'nvarchar(50)') 
                  FROM Records 
                  WHERE boat_id = 2 
                    AND Records.sails.value('local-name(/sails[1]/*[1])', 'nvarchar(50)') = @boat_id );

SELECT 
    [location], Boats.sails.value('(/sails/id10230/sailinfo)[1]', 'nvarchar(50)') AS 'Jib' 
FROM 
    Boats 
FULL JOIN 
    Records ON Records.sails.value('local-name(/sails[1]/*[1])', 'nvarchar(50)') = @boat_id 
WHERE 
    Boats.boat_id = 2;

输出: - https://eval.in/735195

答案 1 :(得分:0)

使用array_intersect_keyarray_diff函数的简短优化解决方案:

$array1 = ["Peter"=>"35", "Ben"=>"21", "Joe"=>"43"];
$array2 = ["Peter"=>"35", "Ben"=>"37", "Joe"=>"57", 'I'=>0];

// getting all $array2 items with coincident keys
$common_key_items = array_intersect_key($array2, $array1);

// getting value difference between arrays with same keys 
$result = array_diff($common_key_items, $array1);

print_r($result);

输出:

Array
(
    [Ben] => 37
    [Joe] => 57
)