将数组值存储在两个数据库表中

时间:2021-04-27 17:00:04

I have an array, I just print it as print_r($data) which looks like-

我有一个数组,我只是将其打印为print_r($ data),看起来像 -

Array
(
    [0] => Array
        (
            [0] => Title
            [1] => Featured Image
            [2] => Catagories
            [3] => Tags
            [4] => Content
        )

    [1] => Array
        (
            [0] => title 1
            [1] => img1.jpg
            [2] => cat 1
            [3] => tag 1
            [4] => post 1 content
        )

    [2] => Array
        (
            [0] => title 2
            [1] => img2.jpg
            [2] => cat2
            [3] => tag 2
            [4] => post 2 content
        )

    [3] => Array
        (
            [0] => title 3
            [1] => img3.jpg
            [2] => cat3
            [3] => tag3
            [4] => post 3 content
        )
}  

I have two tables-
1) sa_posts
2) sa_terms
In sa_posts table I want to store title, feature image, content and in sa_terms table I have to store categories and tags.
How is this possible using foreach or for loop?

我有两个表 - 1)sa_posts 2)sa_terms在sa_posts表中我想存储标题,特征图像,内容,在sa_terms表中我必须存储类别和标签。如何使用foreach或for循环?

2 个解决方案

#1


1  

Get array values by keys, and write insert query for below values

按键获取数组值,并为以下值写入插入查询

<?php 
 foreach($data as $d)
 {
    //sa_posts values title=$d[0],  feature image=$d[1], content = $d['4']
    //sa_terms values categories =$d[2], tags=$d[3]
 }

?>

#2


1  

Foreach is your friend with arrays.

Foreach是你的阵列朋友。

foreach($array as $element) {
  //sql insert to sa_posts for $element[0], $element[1], $element[2]
  //sql insert to sa_terms for $element[3], $element[4]
}

Personally, I've not seen an array whose first element describes the contents of the rest, though. If this isn't common practice, I'd consider using an associative array instead otherwise you'll be forever skipping the first element of your array and if you forget, you're going to end up with some weird data.

就个人而言,我没有看过一个数组,其第一个元素描述了其余部分的内容。如果这不常见,我会考虑使用关联数组,否则你将永远跳过数组的第一个元素,如果你忘了,你最终会得到一些奇怪的数据。

#1


1  

Get array values by keys, and write insert query for below values

按键获取数组值,并为以下值写入插入查询

<?php 
 foreach($data as $d)
 {
    //sa_posts values title=$d[0],  feature image=$d[1], content = $d['4']
    //sa_terms values categories =$d[2], tags=$d[3]
 }

?>

#2


1  

Foreach is your friend with arrays.

Foreach是你的阵列朋友。

foreach($array as $element) {
  //sql insert to sa_posts for $element[0], $element[1], $element[2]
  //sql insert to sa_terms for $element[3], $element[4]
}

Personally, I've not seen an array whose first element describes the contents of the rest, though. If this isn't common practice, I'd consider using an associative array instead otherwise you'll be forever skipping the first element of your array and if you forget, you're going to end up with some weird data.

就个人而言,我没有看过一个数组,其第一个元素描述了其余部分的内容。如果这不常见,我会考虑使用关联数组,否则你将永远跳过数组的第一个元素,如果你忘了,你最终会得到一些奇怪的数据。