0

I have an some data I'm working with that has lots of fields and subfields and subsubfields like:

{field: value;
field: value;
field: [
   {field:value;
    field:value;
    field: [
       {field:value;}
    ]}
]}

We went with a Mysql db (maybe that was a mistake). I'm writing a PHP script right now to get data from the API and insert it into the db. And I'm getting held up on the design pattern to use. I would think something like:

function() insertArrayIntoTable($tableName, $array){}

Would work... but I got held up on having to keep track of ID fields within the parent array and how to pass that to MULTIPLE offspring, who in turn have multiple offspring. So I didn't even bother trying to write something like:

function() insertArrayIntoTable($tableNames, $array, $parentNames){
   for($i=0;$i<count($array);$i++){
      if(is_array($array[$i])){insertArrayIntoTable($tableNames[$i],$array[$i],$parentNames[]);}
   }
}

Because I was afraid to write a function that calls ITSELF in some sort of nested loop.... it just seems wrong. Any advice?

1
  • 1
    if you don't know how much nested field you will have, you don't have much choice other than using a recursive function like the one you showed. just remember to send a return back to keep going with the "second array element" Commented Sep 29, 2017 at 21:03

2 Answers 2

1

MySQL isn't that bad, so it's fine to use it.

Writing a function that calls itself is also not wrong, as you are traversing through a tree with a variable amount of children / children's children, etc. It will probably be necessary to do recursion.

If you are just trying to store an array as a field, make sure you store it as json format and convert it to a string, and that the field for the array is VARCHAR type

Sign up to request clarification or add additional context in comments.

1 Comment

thanks! Even just writing out some pseduo code has made me think... 'why not just try it?'
1

In this case, you can use recursion. A default value is required for the parent.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.