Home > Blockchain >  How can I merge array of arrays fetched from database?
How can I merge array of arrays fetched from database?

Time:10-06

I fetched all codes user got from the database and they are returned as arrays of arrays. How could I merge them so that the codes were sequentially in a one-dimensional array? Unfortunately, I can't change query of the procedure:

Code:

function loadGlobalPermissions(){
    global $pdo;
    $user_id = $_SESSION['id'];
    $sql="CALL skaj_listp(:user_id)";
    $statement = $pdo->prepare($sql);
    $statement->bindParam(':user_id',$user_id,PDO::PARAM_STR);
     if($statement->execute()){
          $response[] = $statement->fetchALL(PDO::FETCH_ASSOC);
        }
        return $response;
}

Array:

array(1) { [0]=> array(1) { [0]=> array(28) { [0]=> array(1) { ["kod"]=> string(2) "DR" } [1]=> array(1) { ["kod"]=> string(3) "DRW" } [2]=> array(1) { ["kod"]=> string(2) "ER" } [3]=> array(1) { ["kod"]=> string(4) "ERDD" } [4]=> array(1) { ["kod"]=> string(5) "ERDSP" } [5]=> array(1) { ["kod"]=> string(4) "ERED" } [6]=> array(1) { ["kod"]=> string(5) "EREFP" } [7]=> array(1) { ["kod"]=> string(4) "EREM" } [8]=> array(1) { ["kod"]=> string(5) "EREMA" } [9]=> array(1) { ["kod"]=> string(4) "EREO" } [10]=> array(1) { ["kod"]=> string(4) "EREP" } [11]=> array(1) { ["kod"]=> string(4) "ERES" } [12]=> array(1) { ["kod"]=> string(4) "ERET" } [13]=> array(1) { ["kod"]=> string(4) "EREU" } [14]=> array(1) { ["kod"]=> string(5) "EREWM" } [15]=> array(1) { ["kod"]=> string(4) "ERUD" } [16]=> array(1) { ["kod"]=> string(5) "ERUSP" } [17]=> array(1) { ["kod"]=> string(2) "EU" } [18]=> array(1) { ["kod"]=> string(3) "EUS" } [19]=> array(1) { ["kod"]=> string(6) "EUSEUP" } [20]=> array(1) { ["kod"]=> string(3) "EWR" } [21]=> array(1) { ["kod"]=> string(3) "LRW" } [22]=> array(1) { ["kod"]=> string(5) "LUDDG" } [23]=> array(1) { ["kod"]=> string(5) "LUUZG" } [24]=> array(1) { ["kod"]=> string(3) "LUW" } [25]=> array(1) { ["kod"]=> string(2) "UR" } [26]=> array(1) { ["kod"]=> string(2) "UW" } [27]=> array(1) { ["kod"]=> string(3) "WPA" } } } } string(4) 

CodePudding user response:

Here's a function i wrote for you to merge a multidimensional array of any depth and return a one-dimensional array. Use it to merge your multidimensional array:

function mergeMultidimensionalArray($array, $merged = [], $depth = 0)
{
    foreach($array as $key => $value) {
        if(is_array($value)) {
            $merged = mergeMultidimensionalArray($value, $merged, $depth  );
        } else {
            if(isset($merged[$key])) {
                $merged[$key . $depth] = $value;
            } else {
                $merged[$key] = $value;
            } 
        }
    }
    return $merged;
}

$merged = mergeMultidimensionalArray($response);
  • Related