试图用单引号包装php变量

时间:2014-06-13 15:17:11

标签: php

我想在variable中将PHP打包成单引号。这是我的代码:

$my_post = array(
            'post_title' => $orderRequestCode.' - ' . $customerName,
            'post_content' => $orderContent,
            'post_status' => 'draft',
            'post_author' => "'".$user_ID."'",
            'post_type' => 'orders'
            );

目前var_dump($my_post)输出:

array (size=5)
  'post_title' => string '2014-06-13-15-13-52 - xxxxxxx' (length=35)
  'post_content' => string 'Order Code: 2014-06-13-15-13-52
   Customer Name: xxxxxxxxxxxx
   Customer Email: xxx@xxxx.xx
   Order Items: 
   Stock Code: Q20-50-6101 Quantity: 12
   Comments: 
' (length=162)
  'post_status' => string 'draft' (length=5)
  'post_author' => string ''1'' (length=3)     <--------------- should be '1'
  'post_type' => string 'orders' (length=6)

这一行:

'post_author' => string ''1'' (length=3)

需要:

'post_author' => string '1' (length=3)

2 个答案:

答案 0 :(得分:4)

var_dump中的外部引号实际上不是字符串的一部分,因此长度为3而不是5.如果您回显字符串,则为'1'

答案 1 :(得分:3)

不,你告诉PHP创建一个3个字符的字符串:

$x = 1;

$y = "'" . $x . "'";
$y = ' 1 '
     1 2 3

由于它是一个字符串,因此当您进行转储时,它也会被OTHER '包裹。如果你的ID是一个整数,并且你希望它被视为一个字符串,那么你可以这么简单:

 'post_author' => (string)$user_ID // cast to string
or
 'post_author' => '' . $user_ID; // concatentate with empty string