s1nb2
s1nb2

Reputation: 82

Php Convert Multidimensional array to string

Below is my function:

public function getChildrenId(){
    $child_id =  array($this->db->query("SELECT customer_id
                              FROM " . DB_PREFIX . "customer
                              WHERE parent IN ( " .(int)$this->customer->getId().") "));
    foreach($child_id as $id =>$value) {
        $conv = json_decode(json_encode($value), true);
        $final = array_slice($conv,2);
        foreach ($final as $gchildren => $key) {
            sort($key);
            $gr = array_slice($key,0,$this->INF);
        }
    }
    return $gr;
}

It outputs:

array (size=3)
  0 => 
    array (size=1)
      'customer_id' => string '2' (length=1)
  1 => 
    array (size=1)
      'customer_id' => string '4' (length=1)
  2 => 
    array (size=1)
      'customer_id' => string '7' (length=1)

I am trying to get the values of the nested arrays. When I use foreach I only get data from array[0]. I also tried slicing the parent array and still didn't get it right, it outputs array,array,array.

I would like to extract these arrays values to a new array that I can use to query the database. final_array = array (2,4,7). Thank you in advance!

Upvotes: 1

Views: 337

Answers (1)

atoms
atoms

Reputation: 3093

If your array looks like this, then the foreach should create the array your looking for.

array (size=3)
  0 => 
    array (size=1)
      'customer_id' => string '2' (length=1)
  1 => 
    array (size=1)
      'customer_id' => string '4' (length=1)
  2 => 
    array (size=1)
      'customer_id' => string '7' (length=1)

The following php will output array(2,4,7);

<?php

$aNewArray = array();

foreach($aArray as $aArray){

    $aNewArray[] = $aArray['customer_id'];

}

var_dump($aNewArray);

?>

You dont need a multidimensional array for this though.

Upvotes: 2

Related Questions