简体   繁体   中英

inarray 2d array

I have a 2d array

$list['1'][] ='23';
$list['1'][] ='24';
$list['1'][] ='25';
$list['1'][] ='26';

And a 1d array

$items={"23","24","36"};

following is right syntax for 1d array.

$items=array("23","24","36");

I want to check whether the $List['1'] values are inside the $items are not, if the items are not then store them into a new array

I tried

$different['1'][] = array_diff($items,$list['1']);

but if there are no difference it creates an array with key but empty value

$different['1]

['1'] => Array
    (
        [0] => 
    )
if($diff = array_diff($items,$list['1])){
     $different['1'][] = $diff;
}

This should do the trick

I cannot reproduce this behaviour.

<?php
echo 'php: ', PHP_VERSION, "\n";
$list = array(1=>array());
$list[1][]=23;
$list[1][]=24;
$list[1][]=25;
$list[1][]=26;

$items = array(23,24);

var_dump(array_diff($items,$list[1]));

prints on my machine

php: 5.4.1
array(0) {
}

try this:

$item = array('23','24');
foreach($list['1'] as $listItem) {
    if(!in_array($listItem, $item)) {
        $different['1'][] = $listItem;
    }
}
$list['1'][] ='23';
$list['1'][] ='24'; 

$items=array("23","24");

$different['1'][] = array_diff($items,$list['1']);

var_dump($different['1']); // output: array(1) { [0]=> array(0) { } }

$different['1'] = array_diff($items,$list['1']);

var_dump($different['1']); // output: array(0) { }
      $list['1'][] ='23';
    $list['1'][] ='24';
    $list['1'][] ='25';
    $list['1'][] ='26';

    $items=array("23","24");

$different['1'][] = array_diff($list['1'],$items);

your arr_diff function's argument sequence was wrong. thats why it will give you null. try above code.

Use for loop for every element in $list array and add following code in that loop

if(!in_array($list[1][0], $items)){
  array_push($items, $list[1][3]);
}

print_r($items);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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