Home > database >  How to sort array with same value in foreach php
How to sort array with same value in foreach php

Time:10-13

I have following array,And i want to merge array value where "location" match, In other words i want to merge array value(text) where "location" similar Here is my current array

Array
(
    [0] => Array
        (
            [id] => 11
            [column_name] => Accommodation
            [text] => school
            [location] => B3
            [match] => 3
        )

    [1] => Array
        (
            [id] => 12
            [column_name] => Accommodation
            [text] => test
            [location] => B3
            [match] => 3
        )

    [2] => Array
        (
            [id] => 13
            [column_name] => Incidental Expenses
            [text] => you
            [location] => C3
            [match] => 3
        )
)

Here is my expected output ( merge "text" according to "location" , because location match)

Array
(
    [0] => Array
        (
            [id] => 11
            [column_name] => Accommodation
            [text] => school , test
            [location] => B3
            [match] => 3
        )
    [1] => Array
        (
            [id] => 13
            [column_name] => Incidental Expenses
            [text] => you
            [location] => C3
            [match] => 3
        )
)

I tried with following code but not working

foreach ($result as $key =>$element) {
    foreach ($result as $search_key => $search_array) {
        if ($search_array['loc'] == $element['loc']) {
            if ($search_key != $key) {
                if($search_key == '1'){
                    $run = $element['text'];
                    $mystring3 = explode(', ',$run);
                    foreach ($mystring3 as $fast){
                        //echo $fast;    
                    }
                }
            }
        }
    }

CodePudding user response:

Use an array were we use the location as key.

If there is already something set on that lcoation, just append the text field, otherwise, set the whole array as the value for that location

<?php

$inputs = [
    [ "id" => 11, "text" => "school", "location" => "B3" ],
    [ "id" => 12, "text" => "test", "location" => "B3" ],
    [ "id" => 13, "text" => "you", "location" => "C3" ],
];

$result = [];
foreach ($inputs as $input) {
    if (isset($result[$input['location']])) {
        $result[$input['location']]['text'] .= ', ' . $input['text'];
    } else {
        $result[$input['location']] = $input;
    }
}
var_dump($result);

Gives:

array(2) {
  ["B3"]=>
  array(3) {
    ["id"]=>
    int(11)
    ["text"]=>
    string(12) "school, test"
    ["location"]=>
    string(2) "B3"
  }
  ["C3"]=>
  array(3) {
    ["id"]=>
    int(13)
    ["text"]=>
    string(3) "you"
    ["location"]=>
    string(2) "C3"
  }
}

Try it online!

  • Related