php从数组中删除值

时间:2012-07-08 20:39:14

标签: php arrays

需要帮助替换数组值  我正在尝试检查经验和空间存在于下面的数组中并用经验max替换空间(i,e下一个数组值,如果它等于null / space替换为经验max), 我已经粘贴了下面的代码,我用它来查找和替换数组值,它取代了经验来体验max而不是空来体验最大值

array[1] => name,
array[2] => Work Experience,
array[3] => ,
array[4] => company,
array[5] => location

o / p:

array[1] => name,
array[2] => Work Experience,
array[3] => Work Experience Max,
array[4] => company,
array[5] => location

$search = "Work Experience";
foreach ($val as $key=> $cnt) {
    // echo "inside foreach ".$cnt;
    if ($cnt == $search) {
        echo  $keyvalue = $key;
        break;
    }
}
if (isset($keyvalue)) {
    $firstarryval = array_splice($val, $keyvalue, 1);
}

if ($firstarryval == '') {
    array_splice($val, $keyvalue, 0, "Work Experience Max");
} else {
    array_splice($val, $keyvalue, 0, "Work Experience Max");
}

1 个答案:

答案 0 :(得分:0)

好的,这里解释的解决方案是:

$arr = array( 0=>'name', 1=>'Work Experience', 2=>'', 3=>'company', 4=>'location' );
var_export($arr); echo '<br/>';
$search = "Work Experience";
$arrkey = false;
foreach($arr as $key=>$value){ // set variables and advance internal pointer
    echo "inside foreach $key => $value <br/>";
    if( $value == $search ) {
        echo $key;
        echo $arrkey = key($arr); // internal php pointer already points to next array key
        break;
    }
}
if ($arrkey!=false && empty($arr[$arrkey])) {
    $arr[$arrkey] = 'Work Experience Max';
}
echo '<br/>'; var_export($arr);

有用的链接:foreachkeyempty。希望它会有所帮助! : - )