繁体   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