php remove duplicates from multidimensional array by value

前端 未结 4 940
臣服心动
臣服心动 2020-12-20 13:52

I would like to remove duplicates by value as you can see from the list_title. I know there are several questions and answers to this but their solution doesn\'

4条回答
  •  一整个雨季
    2020-12-20 14:27

    So basically you want to remove duplicates by 'list_title' column. Let's assume we keep the first occurrence of this title. Then you can use a couple of standard functions to achieve this:

    // Reverse array, so the first occurrence kept.
    $data = array_reverse($data);
    
    $result = array_reverse( // Reverse array to the initial order.
        array_values( // Get rid of string keys (make array indexed again).
            array_combine( // Create array taking keys from column and values from the base array.
                array_column($data, 'list_title'), 
                $data
            )
        )
    );
    

    Here is working demo.

    UPDATE:

    Based on @mickmackusa comment, the code can be simplified to:

    $result = array_reverse(array_values(array_column(
        array_reverse($data),
        null,
        'list_title'
    )));
    

    This is described in the docs regarding column_key parameter specs:

    It may also be NULL to return complete arrays or objects (this is useful together with index_key to reindex the array).

提交回复
热议问题