简体   繁体   English

PHP用方括号替换数组键到数组值

[英]php replace array key with square brackets to array value

I have a string that contain a mysql query: 我有一个包含mysql查询的字符串:

$string = "UPDATE [table1] SET value = 1 WHERE id = 1";

I would like to change [table1] with the value of this array: 我想用此数组的值更改[table1]:

$table['table1']='pages';
$table['table2']='products';
etc

The result should be: 结果应为:

mysql_query( $string ); // "UPDATE pages SET value = 1 WHERE id = 1"

I already tried the following but nothing: 我已经尝试了以下方法,但是什么也没做:

mysql_query( str_replace( '[', '$table[', $string ));
mysql_query( str_replace( array_keys( "[$table]" ), array_values( $table ), $string ));
mysql_query( str_replace( array_keys( "[".$table."]" ), array_values( $table ), $string ));

EDIT This way works, but there is no a easiest way? 编辑这种方法有效,但是没有最简单的方法吗?

str_replace( explode( ',', ( '['.implode( '],[',array_keys( $table ) ) .']' ) ), $table, $string );

What about this 那这个呢

$table['table1']='pages';
$table['table2']='products';

$string = "UPDATE [table1] SET value = 1 WHERE id = 1";

foreach($table as $key => $value){
    $string = str_replace('['.$key.']', $value, $string);
}

那么简单的方法呢?

$string = "UPDATE ".$table['table1']." SET value = 1 WHERE id = 1";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM