使用json&PHP时,是否可以在元标题中添加$ currentProduct的标题?
问题描述:
是否有可能做这样的事情来获得$currentProduct
称号元标题显示:
<?php
$root = $_SERVER["DOCUMENT_ROOT"];
$pageTitle = "Company Name | Our Products - <?php echo $currentProduct->title ?>";
?>
$productTitle = $currentProduct->title;
答
不知道有关的代码顺序和标签是正确的,但:
假设您将JSON字符串转换为JSON对象,可以。 在PHP中,你有两个选择: 要么你继续你的$ currentProject为stdClass对象,或者你把它转换成一个数组:
// STDClass Object (Access with 'STDObject->key' returns value)
$currentProduct = json_decode($json_string); // Converts to STDClass Object
// Array Object (Access with Array[key] returns value)
$currentProduct = json_decode($json_string, true); // Converts to Array Object
随着和stdClass的对象:
1:
// Use '{' and '}' to specify the interpreter you're dealing with an object.
$pageTitle = "Company Name | Our Products - {$currentProduct->title}"; // assuming $currentProduct is a String at least
2:
// Using ' single quotes with this case is better
// but you can't put the variable inside it. (Not that you need it in this case)
$pageTitle = 'Company Name | Our Products - '.$currentProduct->title; // Concatenate the string
3:
$pageTitle .= $currentProduct->title;
现在相同的,但以与阵列对象:
1:
// Use '{' and '}' to specify the interpreter you're dealing with an object.
$pageTitle = "Company Name | Our Products - {$currentProduct['title']}"; // assuming $currentProduct is a String at least
2:
// Using ' single quotes with this case is better
// but you can't put the variable inside it. (Not that you need it in this case)
$pageTitle = 'Company Name | Our Products - '.$currentProduct['title']; // Concatenate the string
3:
$pageTitle .= $currentProduct['title'];
注:
对于PHP解释器中必须使用“双引号的字符串内代价─变量通吃。 至于大括号:
«与串 表示任何标量变量,数组元素或对象属性可以通过该语法包括在内。只需使用与字符串外部相同的方式编写 表达式,然后 将其包装在{和}中。由于{不能被转义,这个语法将只在$紧跟在{之后才会被识别出来, 。用{\ $到 得到一个文字{$。»
看看这个answer。