2017-01-22 112 views
0

请告诉我我在做什么错在这里... PHP版本5.6.27使用wordpress 4.7.1。我将它创建为一个自定义插件。我的页面返回结果为“失败”,尝试了两个不同的页面标题,并且都返回“失败”,这告诉我它没有得到页面标题(位置)在函数中,并且函数失败返回else。PHP函数不返回键

$locations = array(
    array(
     'location' => 'About', 
     'telephone' => '0121 34838383', 
     'email'  => '[email protected]' 
    ) 
); 

function telephone_shortcode() { 
    global $locations; 
    $title = get_the_title(); 
    $key = array_search($title, array_column($locations, 'location')); 
    if ($key) 
     return $locations[$key]['telephone']; 
    else 
     return 'fail'; 
} 
add_shortcode('telephone', 'telephone_shortcode'); 

[电话] - 回报,如果被搜索的元素是在阵列中的第一个元素“失败”

回答

2
array_search

返回0。 0 ==在php假(查找“在PHP truthy值”)更改if语句其他

if($key !== false) 

一切检查可以保持不变。使用!==告诉php检查值是否完全匹配。

+1

太棒了!谢谢 :) –

2

对于此配置,当你只有一个页面的“关于”这样的结果:

array_search($title, array_column($locations, 'location')); 

为0。而当你在这个检查:

if ($key) 

的“如果” $ key参数等于false(因为它的值为零)。使这个功能是这样的:

function telephone_shortcode() { 
    global $locations; 
    $title = get_the_title(); 
    $key = array_search($title, array_column($locations, 'location')); 
    if (false !== $key) 
     return $locations[$key]['telephone']; 
    else 
     return 'fail'; 
} 

和一切都开始工作。教育阅读PHP Dock:http://php.net/manual/en/language.types.boolean.php#language.types.boolean.casting