简体   繁体   English

in_array函数无法正常工作

[英]in_array function not working right

I am using a multidimensional array to hold the variables for a given page. 我正在使用多维数组来保存给定页面的变量。 I am trying to get a string from the url and match it with an array within my template array to pull the correct variables to display on the page. 我试图从url中获取一个字符串,并将其与我的模板数组中的数组匹配,以拉出正确的变量以显示在页面上。

Here is my array: 这是我的数组:

$template = array(

    "index" => array(
        "title" => "Dashboard",
        "model" => "model/dash.php"
    ),
    "input" => array(
        "title" => "Dashboard",
        "model" => "model/input.php"
    ),
    "jobboard" => array(
        "title" => "Job Board",
        "model" => "model/job_board.php"
    ),
    "jobcreate" => array(
        "title" => "Job Creator",
        "model" => "model/job_create.php"
    )
);

And here is what I am using to try and verify the pages: 这是我用来尝试验证页面的内容:

if(isset($_GET['page'])){ $page = $_GET['page']; }

if(in_array($page, $template)){
    $title = $template[$page]['title'];
    $model = $template[$page]['model'];
    echo "yes";
}else{
    $title = $template['index']['title'];
    $model = $template['index']['model'];
    echo "no";
}

The echo "yes/no"; echo "yes/no"; is what I am using to debug if it is working or not but no matter what I have done it just keeps on outputting no. 是我用来调试的工具,不管它是否正常运行,但是不管我做了什么,它只会一直输出no。

in_array() looks at values. in_array()查看值。 It is probably keys you're after. 这可能是您需要的钥匙。

You can check that with array_key_exists() . 您可以使用array_key_exists()进行检查。

Take a look at the documentation of php's in_array() 看看php in_array()的文档

in_array — Checks if a value exists in an array in_array —检查数组中是否存在值

It looks like your intention is to check against the index of the array, rather than the value. 看来您的意图是要检查数组的索引,而不是值。 The values in the array are arrays. 数组中的值是数组。

Try using array_key_exists() instead. 尝试改用array_key_exists()

if (array_key_exists($page, $template)) {
  $title = $template[$page]['title'];
  $model = $template[$page]['model'];
  echo "yes";
}
else {
  $title = $template['index']['title'];
  $model = $template['index']['model'];
  echo "no";
}

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

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