How to get the keys of empty elements in an array if the corresponding element in a similar-sized array is a number (without iteration)?

安稳与你 提交于 2019-12-24 08:39:11

问题


I have two same-sized arrays $array1 and $array2, both with the usual consecutive numerical keys. $array1 contains numbers, $array2 contains text. I cannot change this structure to accommodate multi-dimensional arrays or what.

Without going through the whole array, how do I get the keys i of the elements in $array2 where

  1. $array1[i] is a number; BUT
  2. $array2[i] is empty?

For example:

// numbers
$array1 = array(NAN, NAN, 1, 0, 3.5, NAN, 2, 4, 0.5);

// text
$array2 = array(FALSE, FALSE, "abc", "abc", FALSE, FALSE, "text", "abc", FALSE);

expected result:

// keys of $array2 where $array1[i] is a number and
// $array2[i] is empty/null/false

Array
(
    [0] => 4
    [1] => 8
)

I've been trying to implement array_keys() and array_udiff() and other PHP array functions to do this but I just can't.

Help, guys, thanks!


回答1:


This will perform in linear O(n) time.

$keys = array();
foreach ($array1 as $i => $v1) {
    if (is_numeric($v1) && !$array2[$i])
        $keys[] = $i;
}

is_numeric() accepts a little more than what most people consider "numbers", but if that's a problem just replace with another function.

I also assumed your definition of "empty" is a value that php would convert to boolean false. Again, adjust as necessary.




回答2:


i'd do something like this:

<?php
    $keys = array();
    foreach($array1 as $iterator){
        $key = array_search($iterator,$array1);
        $elem_in_array1 = $array1[$key]; //= $iterator
        $elem_in_array2 = $array2[$key];
        if(is_numeric($elem_in_array1) && emtpy($elem_in_array2)){
            $keys[] = $key;
        }
    }
?>



回答3:


This will grab the first value in $arr1 that matches $value, as well as the corresponding value in $arr2 at the index of the value found in $arr1.

<?php

function array_magic ($value, $arr1, $arr2) {
    $index = array_search($value, $arr1);

    if ($index === false) {
        return false;
    }

    if(!isset($arr2[$index])) {
        $value2 = null;
    } else {
        $value2 = $arr2[$index];
    }

    return array( $value, $value2 );
}


来源:https://stackoverflow.com/questions/8657305/how-to-get-the-keys-of-empty-elements-in-an-array-if-the-corresponding-element-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!