将数据从php中的多维数组插入MySQL [英] Inserting data into MySQL from a multidimensional array in php

查看:68
本文介绍了将数据从php中的多维数组插入MySQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查询的 API 返回以下数据,我使用 json_decode 将这些数据放入数组.我需要提取某些值以插入 MySQL 数据库.在下面的示例中(只有一个 ID),我想插入 ID = 4229850 和 2011(Vanguard 字段的值).我不知道如何在数组中导航并生成适当的插入语句.

An API I am querying returns the following data which I've used json_decode to put into an array. I need to extract certain values for inserting into a MySQL database. In the example below (which only has one ID), I want to insert ID = 4229850 and 2011 (the value of the field Vanguard). I'm can't figure out how to navigate through the array and generate the appropriate insert statement.

Array 
    ( 
    [Contacts] => Array 
        ( 
        [0] => Array 
            ( 
            [Id] => 4229850 [Url] => https://abc.com 
            [FirstName] => Mol 
            [LastName] => Thompson 
            [FieldValues] => Array 
                (
                [0] => Array 
                    (
                    [FieldName] => Profile last updated [Value] => 
                    ) 
                [1] => Array 
                    (
                    [FieldName] => First name [Value] => Mol 
                    [CustomAccessLevel] => Public
                    )
                [2] => Array 
                    (
                    [FieldName] => Last name [Value] => Thompson 
                    )
                [3] => Array 
                    (
                    [FieldName] => e-Mail [Value] => abc@yahoo.ca
                    )
                [4] => Array 
                    (
                    [FieldName] => Vanguard [Value] => 2011
                    ) 
                )
            )
        ) 
    )

推荐答案

$field1=$yourArray['contacts'][0]['Id'] //Value 4229850
$field2=$yourArray['contacts'][0]['FieldValues'][4]['Value'] //Value 2011

使用 PDO 方法

$sql = "INSERT INTO yourTable (field1,field2) VALUES (:field1,:field2)";
$q = $conn->prepare($sql);
$q->execute(array(':field1'=>$field1,
                  ':field2'=>$field2));

使用mysql_query函数

Using mysql_query function

mysql_query("INSERT INTO yourTable (field1,field2) VALUES ('$field1','$field2')");

这篇关于将数据从php中的多维数组插入MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆