반응형

PHP에서 2차원(다차원) Array(배열)에 있는 값을 UNSET을 이용하여 삭제 후
array_values을 이용하여 배열의 인덱스를 재 정렬하는 방법입니다.

1. 2차원 배열을 for 반복문을 돌리면서 in_array를 이용하여 원하는 조건을 찾습니다.

2. 해당 조건에 맞는 배열값을 찾았을 때 그 인덱스(index) 정보를 저장을 합니다.

3. 삭제를 해야 하는 인덱스 정보를 이용하여 unset으로 해당 배열을 삭제합니다.
- 삭제를 하고 나면 인덱스 정보가 0, 1, 2, 3 에서 0, 2 만 남게 됩니다.
- 이 상태로 이 배열을 for 반복문을 돌리게 되면 0 인덱스 값은 가져 오지만 2의 인덱스는
  맞지가 않아서 가져 오지 못합니다.

4. array_values를 이용하여 인덱스 값을 재정렬합니다.
- 0, 2의 인덱스가 0,1로 바뀌게 됩니다.

$prd_list = array
(
    array
        (
            'company' => '가',
            'sale_yn' => '판매가능'
        ),
    array
        (
            'company' => '나',
            'sale_yn' => '판매중지'
        ),
    array
        (
            'company' => '다',
            'sale_yn' => '판매가능'
        ),
    array
        (
            'company' => '라',
            'sale_yn' => '판매중지'
        )

);

print_r2($prd_list);

for($i=0;$i<count($prd_list);$i++){

  if(in_array("판매중지", $prd_list[$i]) == true){
    $sale_end[] = $i;
  }
}

print_r2($sale_end);

for( $j=0; $j < count($sale_end); $j++ )
{
  unset($prd_list[$sale_end[$j]]);
}

print_r2($prd_list);

$prd_list = array_values($prd_list);
print_r2($prd_list);

 

PHP 2차원 Array에서 unset후 배열 index 재 정렬 방법

in_array

(PHP 4, PHP 5, PHP 7)

in_array Checks if a value exists in an array

Description

in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] ) : bool

Searches for needle in haystack using loose comparison unless strict is set.

Parameters

needle

The searched value.

Note:

If needle is a string, the comparison is done in a case-sensitive manner.

haystack

The array.

strict

If the third parameter strict is set to TRUE then the in_array() function will also check the types of the needle in the haystack.

Return Values

Returns TRUE if needle is found in the array, FALSE otherwise.

Examples

Example #1 in_array() example

$os = array("Mac", "NT", "Irix", "Linux");
if (
in_array("Irix", $os)) {
echo
"Got Irix";
}
if (
in_array("mac", $os)) {
echo
"Got mac";
}
?>

The second condition fails because in_array() is case-sensitive, so the program above will display:

Got Irix

Example #2 in_array() with strict example

$a = array('1.10', 12.4, 1.13);

if (
in_array('12.4', $a, true)) {
echo
"'12.4' found with strict check\n";
}

if (
in_array(1.13, $a, true)) {
echo
"1.13 found with strict check\n";
}
?>

The above example will output:

1.13 found with strict check

Example #3 in_array() with an array as needle

$a = array(array('p', 'h'), array('p', 'r'), 'o');

if (
in_array(array('p', 'h'), $a)) {
echo
"'ph' was found\n";
}

if (
in_array(array('f', 'i'), $a)) {
echo
"'fi' was found\n";
}

if (
in_array('o', $a)) {
echo
"'o' was found\n";
}
?>

The above example will output:

'ph' was found 'o' was found

반응형

+ Recent posts