簡體   English   中英

PHP in_array 不工作或工作奇怪

[英]PHP in_array doesn't work or work strange

對不起我的英語不好,但我有一些我無法解決的問題。 我有 arrays ,其中包含帶有鍵“標簽”的 arrays (我將稱之為標簽數組)。在某些標簽數組中是相同的值,所以我想創建一個數組,其中包含標簽數組中的值而不重復。

我在標簽數組中的值列表:

=================
php
bootstrap
html
css
=================
php
=================
bootstrap
=================
laravel
=================
php

包含標簽數組的數組示例:

        Array
    (
        [0] => Array
            (
                [id] => 5
                [project_name] => Something 5
                [info_1] => Some test information 1
                [tags] => Array
                    (
                        [0] => php 
                        [1] =>  html 
                        [2] =>  bootstrap 
                        [3] =>  css
                    )
                [img_1] => 1.jpg
            )
         [1] => Array(...)
         [2] => Array(...)
         [3] => Array(...)
         [4] => Array(...)
}

我做了什么來制作新的排序數組:

public function sortTags($data){
        $works_number = $this->getCountWorks(); //count arrays
        $new_arr =  array();
        for($i=0; $i < $works_number; $i++){
            foreach ($data[$i]['tags'] as $key => $val) {
                if(!in_array($val, $new_arr)){
                    array_push($new_arr, $val);
                }
            }
        }
        echo "Debug : <br /> <pre>";
        print_r($new_arr);
        echo "<pre>";
    }

預期:

Array
(
    [0] => php 
    [1] =>  html 
    [2] =>  bootstrap 
    [3] =>  css
    [6] => laravel
)

真正的結果(看看我還有一個數組,其中也是“php”,但 function 對其進行了排序並沒有寫):

Array
(
    [0] => php 
    [1] =>  html 
    [2] =>  bootstrap 
    [3] =>  css
    [4] => php
    [5] => bootstrap
    [6] => laravel
)

那么為什么我的功能不做我想要的(以及如何修復它)以及為什么 function SORTED LAST ELEMENT?

您的代碼不起作用,因為您在某些標簽周圍有空格。 在將它們推入數組之前,您需要對它們進行trim () 如果要對它們進行排序,則需要在數組上調用sort()

public function sortTags($data){
    $works_number = $this->getCountWorks(); //count arrays
    $new_arr =  array();
    for($i=0; $i < $works_number; $i++){
        foreach ($data[$i]['tags'] as $key => $val) {
            $val = trim($val);
            if(!in_array($val, $new_arr)){
                array_push($new_arr, $val);
            }
        }
    }
    sort($new_arr);
    echo "Debug : <br /> <pre>";
    print_r($new_arr);
    echo "<pre>";
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM