Home > OS >  PHP replace characters in array
PHP replace characters in array

Time:01-18

I'm trying to replace quotes and others characters from a mysql result array, using strtr() function. But i got Warning: strtr() expects parameter 1 to be string, array given and null values.

Heres my code:

  while($rows = mysqli_fetch_assoc($list)){

    $string_filter = array(';'=>'','['=>'',']'=>'','{'=>'','}'=>'','"'=>'',"'"=>'');

    $data[$rows['id']] = strtr($rows,$string_filter);

  }

$data is an array that i want to remove/trim the characters specified in $string_filter array. Heres the content sample from $data:

Array ( [1] => Array ( [id] => 1 [user_id] => 204554 [name] => Rich [group] => PL [ai] => BA [image] => 204554-35849.jpg ) [2] => Array ( [id] => 2 [user_id] => 124534 [name] => James [group] => SS [ai] => IT [image] => 123141-12312.jpg )...

CodePudding user response:

Quick Question, are you sure these characters actually exist in your data? Because the characters you are trying to remove are the ones php will automatically append to an array when that array is viewed via the print_r function. To be precise this statement

print_r(array('key' => 'value'));

will output

Array([key] => value)

even tough there is no actual [ or ] present in the arrays data itself.

In any case this code snippet will clean the keys and values of your array:

$string_filter = array(';'=>'','['=>'',']'=>'','{'=>'','}'=>'','"'=>'',"'"=>'');
while($rows = mysqli_fetch_assoc($list)){    
    $cleanedrow = [];
    foreach($rows as $key => $value) {
        $cleanedrow[strtr($key, $string_filter)] = strtr($value, $string_filter);
    }
    $data[$rows['id']] = $cleanedrow;
}
  •  Tags:  
  • Related