简体   繁体   English

从另一个数组中查找数组中的值

[英]find values in array from another array

First Array is 第一个数组是

Array
(
    [2] => Course 1
    [3] => C2
    [4] => COMPUTATIONAL MATHEMATICS -I
    [5] => BASIC ELECTRONICS
    [6] => DATA STRUCTURE
    [7] => COMMUNICATION SKILL
    [8] => SYSTEMS PROGRAMMING 
    [9] => DIGITAL LOGIC 
    [10] => GROUP A:ENGINEERING DRAWING & WORKSHOP
)

my second array is 我的第二个数组是

 Array
    (
        [0] => Array
            (
                [course_id] => 2
            )
        [1] => Array
            (
                [course_id] => 4
            )
        [2] => Array
            (
                [course_id] => 6
            )
        [3] => Array
            (
                [course_id] => 10
            )
    )

my expected result is 我的预期结果是

Array
    (
        [2] => Course 1
        [4] => COMPUTATIONAL MATHEMATICS -I
        [6] => DATA STRUCTURE
        [10] => GROUP A:ENGINEERING DRAWING & WORKSHOP
    )

I would like to find out if first array contains value in second array and return the result array . 我想找出第一个数组是否包含第二个数组中的值并返回结果数组。 any idea please? 有什么想法吗?

Try this 尝试这个

$firstArray = Array();
    $firstArray[2] = "Course 1";
    $firstArray[3] = "C2";
    $firstArray[4] = "COMPUTATIONAL MATHEMATICS -I";
    $firstArray[5] = "BASIC ELECTRONICS";
    $firstArray[6] = "DATA STRUCTURE";
    $firstArray[7] = "COMMUNICATION SKILL";
    $firstArray[8] = "SYSTEMS PROGRAMMING"; 
    $firstArray[9] = "DIGITAL LOGIC";
    $firstArray[10] = "GROUP A:ENGINEERING DRAWING & WORKSHOP";

$secondArray = Array();
$secondArray[0]["course_id"] = 2;
$secondArray[1]["course_id"] = 4;
$secondArray[2]["course_id"] = 6;
$secondArray[3]["course_id"] = 10;

$result = array(); 
foreach($secondArray as $second){
    $result[$second["course_id"]] = $firstArray[$second["course_id"]];
}
echo '<pre>';
print_r($result);

You can do something like this. 你可以做这样的事情。 Define result as array. result定义为数组。 and put second array's values in it by using for loop. 并使用for循环将第二个数组的值放入其中。

$result = array();
foreach($second_array as $sa){
   $result[$sa] = $first_array[$sa];
}

print_r($result);

@Ronak's answer is the correct idea...the keys for the result just need to reference the course_id, otherwise an undefined offset error occurs. @Ronak的答案是正确的想法...结果键只需要引用course_id,否则会发生未定义的偏移量错误。

Sorry, I would have commented but not enough rep yet :) 抱歉,我会发表评论,但代表还不够:)

$result = array();
foreach($second_array as $sa){
   $result[$sa['course_id']] = $first_array[$sa['course_id']];
}

print_r($result);

您需要转换为第二维数组,并在使用array_diff_key()之后

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

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