array_search()错误

时间:2012-07-30 10:12:29

标签: php arrays

数组替换无法正常工作或我遗漏了一些东西。

我想用你的XML文件替换任何等于'读取时出错的错误'的文本'读取已经停止,但当我使用PHP代码低于键 0 得到更新,这是错误的!

有什么想法吗?

由于

原始状态:

Array
(
    [0] => Element 'item', attribute 'isd': The attribute 'isd' is not allowed.
    [1] => Element 'item', attribute 'avai0lable': The attribute 'avai0lable' is not allowed.
    [2] => Unimplemented block at ..\xmlschemas.c:28274
    [3] => An Error Occured while reading
)

PHP代码:

$errors = array_unique($errors);
$key = array_search('An Error Occured while reading', $errors);
$errors[$key] = 'Reading has stopped after fatal error in you XML file';
echo '<pre>'; print_r($errors); echo '</pre>';

结果错误:

Array
(
    [0] => Reading has stopped after fatal error in you XML file
    [1] => Element 'item', attribute 'avai0lable': The attribute 'avai0lable' is not allowed.
    [2] => Unimplemented block at ..\xmlschemas.c:28274
    [3] => Reading has stopped after fatal error in you XML file
)

3 个答案:

答案 0 :(得分:0)

尝试下面的代码,我无法重现你说的话:

<?php
$errors = Array
( "Element 'item', attribute 'isd': The attribute 'isd' is not allowed.",
    "Element 'item', attribute 'avai0lable': The attribute 'avai0lable' is not allowed.",
    'Unimplemented block at ..\xmlschemas.c:28274',
    'An Error Occured while reading',
);
echo '<pre>'; print_r($errors); echo '</pre>';
$errors = array_unique($errors);
$key = array_search('An Error Occured while reading', $errors);
$errors[$key] = 'Reading has stopped after fatal error in you XML file';
echo '<pre>'; print_r($errors); echo '</pre>';
?>

答案 1 :(得分:0)

脚本:

<?php

$data = array (
    0 => "Element 'item', attribute 'isd': The attribute 'isd' is not allowed.",
    1 => "Element 'item', attribute 'avai0lable': The attribute 'avai0lable' is not allowed.",
    2 => "Unimplemented block at ..\xmlschemas.c:28274",
    3 => "An Error Occured while reading"
);

$new_data = array();
$a = "An Error Occured while reading";
$b = "Reading has stopped after fatal error in you XML file";

foreach ( $data as $key => $value ) {
    $new_data[$key] = str_replace( $a, $b, $value );
}

?>

$new_data的输出:

Array
(
    [0] => Element 'item', attribute 'isd': The attribute 'isd' is not allowed.
    [1] => Element 'item', attribute 'avai0lable': The attribute 'avai0lable' is not allowed.
    [2] => Unimplemented block at ..\xmlschemas.c:28274
    [3] => Reading has stopped after fatal error in you XML file
)

答案 2 :(得分:0)

正确的代码是:

$errors = array_unique($errors);
$key = array_search('An Error Occured while reading', $errors);
if($key)
 $errors[$key] = 'Reading has stopped after fatal error in you XML file';
echo '<pre>'; print_r($errors); echo '</pre>'