How to get unique value in multidimensional array

前端 未结 8 1170
盖世英雄少女心
盖世英雄少女心 2020-12-01 03:34

I have done a lot of looking around on the overflow, and on google, but none of the results works for my specific case.

I have a placeholder array called $holder, va

相关标签:
8条回答
  • 2020-12-01 04:07
    $uniquearray = [];
        for($i=0;$i<count($assocarray);$i++){
            if(!in_array($assocarray[$i]['KEY'],$uniquearray)){
                $uniquearray[$i]= $assocarray[$i]['KEY'];
            }
    }
    
    0 讨论(0)
  • 2020-12-01 04:08

    Assuming your array is called $holder:

    $unique = array();
    foreach( $holder as $h )
        if( ! in_array($h, $unique ) )
            $unique[] = $h;
    

    is a slightly more efficient way than via array_unique, I believe. May be the same.

    0 讨论(0)
  • 2020-12-01 04:15

    Hi Please try code given below for get unique values and then sort that values

    <?php
    
    $sort_arr = unique_sort($holder, 'pid');
    echo "<pre>";
    print_r($sort_arr);
    echo"</pre>";
    
    /*function for get unique value then sort them*/
    
    function unique_sort($arrs, $id) {
        $unique_arr = array();
        foreach ($arrs AS $arr) {
    
            if (!in_array($arr[$id], $unique_arr)) {
                $unique_arr[] = $arr[$id];
            }
        }
        sort($unique_arr);
        return $unique_arr;
    }
    

    thanks

    0 讨论(0)
  • 2020-12-01 04:16

    try this

    foreach($arr as $key => $val) {
        $new_arr[] = $val['pid'];
    }
    $uniq_arr = array_unique($new_arr);
    
    0 讨论(0)
  • 2020-12-01 04:16

    fo my situation i use this method

    //get some data from db to array
    while ($row = mysqli_fetch_assoc($query)){
       $data[] = $row;
    }
    
    //display unique value
    echo "<table>";
    $uniq = array();
    foreach ($data as $row) {
        if(!in_array($row['path'], $uniq)) {
            $uniq[] = $row['path'];
            echo "<tr>";
            echo "<td>";
            echo $row['path'];
            echo "</td>";
            echo "<td>";
            echo $row['relationship_id'];
            echo "</td>";
            echo "</tr>";
        }
    }
    echo "</table>";
    
    0 讨论(0)
  • 2020-12-01 04:24

    Seems pretty simple: extract all pid values into their own array, run it through array_unique:

    $uniquePids = array_unique(array_map(function ($i) { return $i['pid']; }, $holder));
    

    The same thing in longhand:

    $pids = array();
    foreach ($holder as $h) {
        $pids[] = $h['pid'];
    }
    $uniquePids = array_unique($pids);
    
    0 讨论(0)
提交回复
热议问题