удаление элемента из многомерного массива php - PullRequest
0 голосов
/ 25 января 2010

Я пытаюсь удалить элемент из многомерного массива в PHP. Вот код:

<?php

$tset = "ST3"; 
$gettc = "gettingtc1"; 
$getbid = "gettingbid1"; 
$getresultsid = "gettingresid1"; 


$users[$tset] = array();


$users[$tset][] = array( "testcase"=>"$gettc", 
                         "buildid"=>"$getbid", 
                         "resultsid"=>"$getresultsid"  
                  ); 


$tset = "TEJ"; 
$gettc = "ggettingtc2"; 
$getbid = "gettingbid2"; 
$getresultsid = "gettingresid2"; 



$users[$tset][] = array( "testcase"=>"$gettc", 
                         "buildid"=>"$getbid", 
                         "resultsid"=>"$getresultsid"  
                  ); 


$tset = "ST3"; 
$gettc = "ggettingtc12"; 
$getbid = "gettingbid13"; 
$getresultsid = "gettigresid14"; 

$users[$tset][] = array( "testcase"=>"$gettc", 
                         "buildid"=>"$getbid", 
                         "resultsid"=>"$getresultsid"  
                  ); 

                  foreach ($users as $val => $yy)
                  {
                  echo "For $val the array is :";
                  foreach($yy as $uy)
                  {
                  echo $uy['testcase'].$uy['buildid'].$uy['resultsid'];

                  }
                  echo '<br>';
                  }


                 $ser = "gettingresid1";

$to = array_searchRecursive($ser,$users);
if($to <> 0)
{
print_r($to);
}

else
{
echo "not";
}


function array_searchRecursive( $needle, $haystack, $strict=true, $path=array() )
{
    if( !is_array($haystack) ) {
        return false;
    }

    foreach( $haystack as $key => $val ) {
        if( is_array($val) && $subPath = array_searchRecursive($needle, $val, $strict, $path) ) {
            $path = array_merge($path, array($key), $subPath);
            return $path;
        } elseif( (!$strict && $val == $needle) || ($strict && $val === $needle) ) {
            $path[] = $key;
            return $path;
        }
    }
    return false;
} 

?>

Где я застрял: $to содержит массив с моим поисковым элементом. Но результаты $to удерживаются должны быть удалены из исходного массива $users.

Любая помощь.

Спасибо.

Ответы [ 2 ]

2 голосов
/ 25 января 2010

Я думаю, что вы хотите использовать unset ()

//assuming $to contains the key in $users that needs to be removed
//from the array
unset($users[$to]);

Но поскольку $to содержит массив ключей для элемента, а не один ключ к элементу, вам нужно написать свои собственные функции, чтобы делать то, что вы хотите.

Функция, которая делает то, что вам нужно, находится ниже, и удалит элемент данного массива с адресом в $ keys.

/**
 * Removes the element with the keys in the array $keys
 *
 * @param haystack the array that contains the keys and values
 * @param keys the array of keys that define the element to remove
 * @return the new array
 */
function array_remove_bykeys( array $haystack, array $keys ){
    //check if element couldn't be found
    if ( empty($keys) ){
        return $haystack;
    }

    $key = array_shift($keys);
    if ( is_array($haystack[$key]) ){
        $haystack[$key] = array_remove_bykeys($haystack[$key], $keys);
    }else if ( isset($haystack[$key]) ){
        unset($haystack[$key]);
    }
    return $haystack;
}

Другой метод - удалить все ключи со значением, которое вы искали.

/**
 * Removes all elements from that array that has the value $needle
 * @param $haystack the origanal array
 * @param $needle the value to search for
 * @return a new array with the value removed
 */
function array_remove_recursive( array $haystack, $needle ){
    foreach( $haystack as $key => $value ) {
        if( is_array($value) ) {
            $haystack[$key] = array_remove_recursive($value, $needle);
        } else if ( $value === $needle ){
            unset($haystack[$key]);
        }
    }
    return $haystack;
}

Для полноты (хотя демонстративно не рекомендуется), вот версия eval:

$keys = array(...);//an array of keys
//$arr is the variable name that contains the value that you want to remove
eval ('unset($arr[\''.implode('\'][\'', $keys).'\']);');
0 голосов
/ 25 января 2010

Передайте $ users в array_searchRecursive по ссылке (добавьте '&' к $ haystack):

function array_searchRecursive( $needle, &$haystack, $strict=true, $path=array()

и затем в array_searchRecursive, непосредственно перед каждым оператором возврата:

unset($haystack[$key]);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...