-1

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

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");
}
4

1 回答 1

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。希望它会有所帮助!:-)

于 2012-07-08T21:47:41.150 回答