1

I have an array like this. This array value will be a dynamic value. So there will be array starting from author0 to authorN (where N represents any numbers). The order will be in the below sequential only.

    Array
    (
        [author0] => 31
        [percent0] => 10
        [start0] => 2014-05-20
        [end0] => 2014-05-21
        [author1] => 70
        [percent1] => 20
        [start1] => 2014-05-21
        [end1] => 2014-05-21
        [author2] => 75
        [percent2] => 20
        [start2] => 2014-05-21
        [end2] => 2014-05-21
    )

I need to store the above array values in db as follows

table name: author_percentage

    author          percentage      start           end
    31              10              2014-05-20      2014-05-21
    70              20              2014-05-21      2014-05-21
    75              20              2014-05-21      2014-05-21

So how can I achieve that?

Thanks, Kimz

3 Answers 3

1

Add an temp array:)

$tempArr = array();
foreach($array as $rows) {
     $tempArr[] = $rows;
     if(count($tempArr) == 4) {
       $query = "INSERT INTO author_percentage ('author','precentage','start','end') VALUES ($tempArr[0],$tempArr[1],$tempArr[2],$tempArr[3])";
       $tempArr = array();
     }
}
Sign up to request clarification or add additional context in comments.

Comments

1

I would do something like this

$i = 0;
while(array_key_exists("author". $i, $array))
{
  $sql = "INSERT INTO author_percentage (author, percentage, start, end) VALUES ('" .         $array['author'.$i] . "', '" . $array['percentage'.$i] . "', '" . $array['start'.$i] . "', '"   . $array['end'.$i] . "')";
  //execute SQL here, like$mysqli::query($sql);
  $i++;
}

assuming that your array is saved within the variable $array.

Comments

0

there is a simpler way to do what you want. It is much elegant to group each index category to individual arrays. //PARENT ARRAY TO STORE CHILDREN $data = array();

//ITERATE YOUR DATA INTO INDIVIDUAL ARRAYS INSIDE PARENT $data ARRAY
while($datasource != 0){
    $data[] = array(
        author  => 31
        percent => 10
        start   => 2014-05-20
        end     => 2014-05-21
);

Now you will have a pretty array tree that you can quickly manipulate using foreach $data[0] = array( author => 31 percent => 10 start => 2014-05-20 end => 2014-05-21 );

$data[1] = array(
    author  => 31
    percent => 10
    start   => 2014-05-20
    end     => 2014-05-21
);

... and so on

Happy coding my friend.

hack some PHP from my blog

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.