Reputation: 79
I am trying to access the values of this array in PHP. It's a multidimensional array. I need to get values from the array and insert it in the DB. Inserting is the second part of the problem. First parts is getting the values from it.
JSON -
{
"itempicture":[
{
"status":"3"
},
{
"ItemCode":"001",
"ItemImage":"image1",
"ItemCategory":"shirt",
"ShowOnPOS":"Yes",
"LastModifiedOn":"2018-06-02 11:53:57"
},
{
"ItemCode":"002",
"ItemImage":"image2",
"ItemCategory":"shirt",
"ShowOnPOS":"Yes",
"LastModifiedOn":"2018-06-02 11:53:57"
}]}
Here the "itempicture" is the table name and all the keys, i.e 'itemcode', 'itemimage, etc are the SQL columns'".
I need to get the values of the SQL columns and insert it into the DB.
So far i have tried this -
$data = file_get_contents($url);
$json_array = (array)(json_decode($data));
print_r($json_array);
foreach($user->itempicture as $mydata)
{
echo $mydata->itempicture . "\n";
foreach($mydata->itempicture as $values)
{
echo $values->itempicture . "\n";
}
}
Using MYSQL in Object-oriented method to insert it in DB, with a simple query like "INSERT INTO table_name VALUES (value1, value2, value3, ...)"
So table name will be the "itempicture" present in the array and values will be the values of the keys in the array.
Upvotes: 0
Views: 1257
Reputation: 12537
There are some issues I have seen in your code:
json_decode($data)
to an array, an then later you try to use property-access to access the "itempicture" property. I have removed this cast.$user
, I guess you meant to use $json_array
.After having fixed this issues the code looks like that and works with your given JSON. I have just echo
-ed the values since you have not told us which DB-abstraction you use, but you can use the values to populate the database.
$data = file_get_contents($url);
$json_array = (json_decode($data));
print_r($json_array);
foreach($json_array->itempicture as $mydata)
{
if (!property_exists($mydata, 'ItemCode')) {
// Ignore entries which are invalid (have no ItemCode property)
continue;
}
echo implode(' - ', [
$mydata->ItemCode,
$mydata->ItemImage,
$mydata->ItemCategory,
$mydata->ShowOnPOS,
$mydata->LastModifiedOn,
]), PHP_EOL;
}
Upvotes: 0
Reputation: 2215
This may be of help. Instead of looping through the properties with a foreach
and printing, you'll want to use them to build an array to use as parameters for a prepared query, or build the query directly. But this shows you how to access those properties -
<?php
$j='{
"itempicture":[
{
"status":"3"
},
{
"ItemCode":"001",
"ItemImage":"image1",
"ItemCategory":"shirt",
"ShowOnPOS":"Yes",
"LastModifiedOn":"2018-06-02 11:53:57"
},
{
"ItemCode":"002",
"ItemImage":"image2",
"ItemCategory":"shirt",
"ShowOnPOS":"Yes",
"LastModifiedOn":"2018-06-02 11:53:57"
}]}';
$jo=json_decode($j);
print("status ".$jo->itempicture[0]->status."\n");
for($i=1;$i<count($jo->itempicture);$i++){
foreach($jo->itempicture[$i] as $prop=>$val){
print($prop." = ".$val."\n");
}
}
?>
Upvotes: 1