如何使用while循环检查和获取in_array的数据?

时间:2019-06-07 11:37:13

标签: php arrays

我有两个表,我想获得仅在数组中匹配的结果,这是数据库: 表fatal: ambiguous argument 'mybranch..master': unknown revision or path not in the working tree中,它存储文章的应用位置

git checkout

pinned,它存储文章

| id | article_id | pinned_sort | apply |
| 1 | 121 | 1 | a:1:{i:0;i:1;} |
| 2 | 148 | 1 | a:3:{i:0;i:2;i:1;i:2;i:2;i:3;} |
| 3 | 210 | 1 | a:3:{i:0;i:3;i:1;i:2;i:2;i:3;} |

这是我的功能

article

但是非常奇怪的是,只有当| aid | title | | 121 | Test 1 | | 148 | Test 2 | | 210 | Test 3 | <?php function getArticlePinned($connectdb, $board_id = '') { $board_id = (int) $board_id; if (!empty($board_id)) { $read['query'] = 'SELECT article.aid, article.title, pinned.apply FROM pinned INNER JOIN article ON article.aid = pinned.article_id ORDER BY pinned_sort ASC'; //Get result $read['stmt'] = $connectdb->stmt_init(); $read['stmt']->prepare($read['query']); $read['stmt']->execute(); $read['result'] = $read['stmt']->get_result(); if ($read['result']->num_rows != 0) { while ($read['row'] = $read['result']->fetch_assoc()) { //Get array from unserialize $pinnedArray = unserialize($read['row']['apply']); if (is_array($pinnedArray)) { //Check if the board id is in array if (in_array($board_id, $pinnedArray) === true) { $result[] = $read['row']; } else { $result = false; } } else { $result = false; } } } else { $result = false; } } else { $result = false; } return $result; } 时,它才能获得结果...

2 个答案:

答案 0 :(得分:1)

我认为您的代码应默认将$ result = false初始化,并让下面的代码按其运行。

function getArticlePinned($connectdb, $board_id = '')
{
    $board_id = (int) $board_id;
    $result   = false;
    if (!empty($board_id)) {
        $read['query'] = 'SELECT
            article.aid,
            article.title,
            pinned.apply
            FROM pinned
            INNER JOIN article ON article.aid = pinned.article_id
            ORDER BY pinned_sort ASC';
        //Get result
        $read['stmt'] = $connectdb->stmt_init();
        $read['stmt']->prepare($read['query']);
        $read['stmt']->execute();
        $read['result'] = $read['stmt']->get_result();
        if ($read['result']->num_rows != 0) {
            while ($read['row'] = $read['result']->fetch_assoc()) {
                //Get array from unserialize
                $pinnedArray = unserialize($read['row']['apply']);
                //Check if the board id is in array
                if (is_array($pinnedArray) && in_array($board_id, $pinnedArray)) {
                    $result[] = $read['row'];
                }
            }
        }
    }
    return $result;
}

Demo

答案 1 :(得分:0)

我的天哪!我修好了它 !!当$result = false;返回false时,我只是删除了in_array,这是代码:

if (in_array($board_id, $pinnedArray) === true) {
    $result[] = $read['row'];
}

代替

if (in_array($board_id, $pinnedArray)) {
    $result[] = $read['row'];
} else {
    $result = false;
}

仍然不知道为什么,但是它能起作用...