0

I'm trying to insert a PHP array into a mysql database, but am having trouble with this particular array. I'm trying to create a function that takes

 array( 0 => array ( 'col1' => 'value', 'col2' => 'value', 'col3' => 'value', 'col4' => value', 'col5' => 'value', 'col6' => array ( 'string' => array ( 'col7' => 'value' , 'col8' => 'value'), ), ), 

    1 => array ( 'col1' => 'value', 'col2' => 'value', 'col3' => 'value', 'col4' => array ( ), 'col5' => 'value', 'col6' => array ( 'string' => array ( ), ),  ),

     2 => array ( 'col1' => 'value', 'col2' => 'value', 'col3' => 'value', 'col4' => array ( ), 'col5' => 'value', 'col6' => array ( 'string' => array ( ), ), ), )

and seperates each numbered array and formats it as:

array( 'col1' => 'value', 'col2' => 'value', 'col3' => 'value', 'col4' => 'value', 'col5' => 'value', ['col6' => 'value','col7' => 'value',] )

array( 'col1' => 'value', 'col2' => 'value', 'col3' => 'value', 'col4' => 'value', 'col5' => 'value', ['col6' => 'value','col7' => 'value',] )

array( 'col1' => 'value', 'col2' => 'value', 'col3' => 'value', 'col4' => 'value', 'col5' => 'value', ['col6' => 'value','col7' => 'value',] )

depending on how many rows there are. Keep in mind these conditions:

+8 cols is just an example, the range can fluctuate greatly. 
+Cols containing a array must be non existent if it empty, like in [1] and [2], but not [0].
+Any column could contain a empty or full array. if it contains a full array, it needs to be flatten while retaining it's value.
+Some arrays might have greater then 2 nested arrays. (elements)  
+Not all of the arrays have nested arrays, they are already formatted correctly. These arrays can not be affected by the PHP function i'm trying to create.

I'm stumped, every function I've created has failed. Thanks everyone in advance.

UPDATE I used Var_export with this function to get the array above.

    function flatten($array, $preserve_keys = false)
{
  if (!$preserve_keys) {
 $array = array_values($array);

  }
  $flattened_array = array();

  foreach ($array as $k => $v) {
   $flattened_array[$k] = $v;
    if (is_array($v)) {

      $flattened_array = array_merge($flattened_array, call_user_func(__FUNCTION__, $v, $preserve_keys));
    } elseif ($preserve_keys) {
      $flattened_array[$k] = $v;
    } else {
      $flattened_array[] = $v;
    }
  }
  return (array)$flattened_array;
}
  • how do you want them to be flattened, should we just add cols, or will it be a string with all the values (instead of array)> – pzirkind Dec 30 '12 at 22:33
  • Thanks @pzirkind, The single key/value containing the array needs to be replaced with the contained col and values. So yes, it needs to be an array still. –  Dec 30 '12 at 22:39
  • ah, so what are we flattening (if the array will still remain) – pzirkind Dec 30 '12 at 22:44
  • sorry just realized what you meant, thanks for clarifying! – pzirkind Dec 30 '12 at 22:51

1 Answers1

0

What you need is what's called a recursive function (see this question for more info: What is a RECURSIVE Function in PHP?).

Also it seems that each "col" in the array is a string (and not a number).

What you might want to try is check whether the first (or any) key in the array is numeric.

The code would look something like this:

public function extractArray($myArray){

    $extractedArray = array(); // create a new array where all the flattened data will go
    $arrayKeys = array_keys($myArray); // grab all the keys from the array
    if (is_numeric($arrayKeys[0])): // if the first key is a number (it's nested)
        $extractedArray = $myArray[0]; // remove one level of the array by grabbing everything from the first element
        extractArray($extractedArray); // run our function again to check if we need to remove another layer
    else:

        $extractedArray = $myArray; // seems like there are no layers that need to be removed
    endif;
    return $extractedArray;
}

Edit:

Here is a possible solution for the second part of the problem (extracting values from possible sub-arrays)

Here are the steps we are going to take:

1) Loop through each element in our $extractedArray (from part 1) and see if it is a sub array

2) If it is an array we extract it's contents and place it in a temporary variable (an array for now)

3) We then call ourselves again (recursively) passing it the new temporary variable (until there are no more sub-arrrays left

4) Once we have extracted all the values and flattened them in to a single array, we can then loop through that array and store them as a string (or whatever else we like)

Updated Code Here is the code:

public function flattenArrayValues($extractedArray){
     $extractedValues = array();
     foreach($extractedArray as $key => $eA):
          if(is_array($eA)): // check whether current element is an array
            reset($eA); // go to the first element of the array and grab it
            $first_key = key($eA); // ...
            $extractedValues[$key] = $eA[$first_key]; // this allows us to preserve the "cols" for each element
            flattenArrayValues($extractedValues); //call ourselves again to check whether there are any sub-arrays
          endif;
     endforeach;
     return $extractedValues; // seems like we extracted all the values and flattened them 
     // if we want we can loop through this new array and build a string out of it etc.
}

Hope this was helpful

Community
  • 1
  • 1
pzirkind
  • 2,338
  • 2
  • 20
  • 25
  • I'm working with xml->json decode so yes, cols and values are all double quoted strings. –  Dec 30 '12 at 23:29
  • this is the problem i'm talking about. your function is great for when you know what index number exists in the array and how many nests there are. Now it only extracts index [0] and the arrays that share a format of no nests, while neglecting all the other cols and values such as [1] and [2]. –  Dec 31 '12 at 00:30
  • It will keep on removing the index[0] (as many layers as needed) because the function checks the result by calling itself – pzirkind Dec 31 '12 at 00:42
  • 1
    Its true that this function doesn't desk with the sub array values, I will try to help you in the morning with this second part – pzirkind Dec 31 '12 at 00:43
  • ty @pzirkind, much appriciated. I've been boggled by this problem for days. –  Dec 31 '12 at 00:44
  • sorry, it is still giving you problems, i will try and fix it tomorrow – pzirkind Jan 02 '13 at 00:09
  • 1
    $extractedValues[$key] = $eA[$first_key]; invalid index. :( –  Jan 04 '13 at 13:08
  • please post how you are using the code so i can better assist (by me it seems to be working fine) – pzirkind Jan 04 '13 at 15:31