打印数组中的字段值

时间:2015-06-26 12:02:40

标签: php

我正在使用找到here的教程来显示基于Drupal中Google Maps Directions API的路线。我的节点中有两个字段 - originfield和destinationfield。每个都包含一个城市的名称。

问题是我无法打印$ params数组中的字段值。这是整个tpl.php代码:

<?php
/**
 * @file
 * Returns the HTML for a node.
 *
 * Complete documentation for this file is available online.
 * @see https://drupal.org/node/1728164
 */
?>

<?php
// This print works:
print $node->field_originfield['und'][0]['value'];

    // Parameters used for the request
    $params = array(
        'origin'    => 'Tokyo, Japan', // I can't find a way to output the originfield's value here
        'destination'   => 'Kyoto, Japan' // I can't find a way to output the destinationfield's value here
    );

    // Join parameters into URL string
    foreach($params as $var => $val){
        $params_string .= '&' . $var . '=' . urlencode($val);  
    }

    // Request URL
    $url = "http://maps.googleapis.com/maps/api/directions/json?".ltrim($params_string, '&');

    // Make our API request
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $return = curl_exec($curl);
    curl_close($curl);

    // Parse the JSON response
    $directions = json_decode($return);

    // Show the total distance
    print('<p><strong>Total distance:</strong> ' . $directions->routes[0]->legs[0]->distance->text . '</p>');

?>

// This print works:
<?php
print $node->field_originfield['und'][0]['value'];
print $node->field_destinationfield['und'][0]['value'];
?>

如果我手动添加原点和目的地,一切正常。但是,如果我使用以下任何一种组合,整个页面都会搞砸,没有显示任何内容或根本没有任何结果。

'origin'    => "<?php print $node->field_originfield['und'][0]['value']; ?>"
'origin'    => "print $node->field_originfield['und'][0]['value'];"
'origin'    => "$node->field_originfield['und'][0]['value'];"
'origin'    => "field_originfield['und'][0]['value'];"
'origin'    => "field_originfield;"
'origin'    => "<?php print render($content['originfield']); ?>"

我也试过这个,没有运气:

$departure = print $node->field_originfield['und'][0]['value'];
$arrival = print $node->field_destinationfield['und'][0]['value'];

'origin' => 'departure',
'destination'   => 'arrival'

我在这里做错了什么?

2 个答案:

答案 0 :(得分:2)

请试试这个:

$params = array(
    'origin'    => $node->field_originfield['und'][0]['value'],
    'departure' => $node->field_destinationfield['und'][0]['value']
);

$departure = $node->field_originfield['und'][0]['value'];
$arrival = $node->field_destinationfield['und'][0]['value'];

$params = array(
    'origin' => $departure,
    'destination'   => $arrival
);

答案 1 :(得分:2)

试试这个

$departure = $node->field_originfield['und'][0]['value'];
$arrival = $node->field_destinationfield['und'][0]['value'];

'origin' => $departure,
'destination'   => $arrival