How to save this JSON stringified array into database? [duplicate] - php

This question already has answers here:
how to save json model object to php mysql database
(2 answers)
Closed 5 years ago.
I have a form that submitted a stringified JSON array. This is the data example:
"[{'name':'i_cp_nm','value':'1'},{'name':'i_cp_tp','value':'2'},{'name':'i_cp_mb','value':'3'},{'name':'i_cp_em','value':'4'},{'name':'i_cp_jb','value':'5'},{'name':'i_cp_nt','value':'6'},{'name':'i_cp_nm','value':'7'},{'name':'i_cp_tp','value':'8'},{'name':'i_cp_mb','value':'9'},{'name':'i_cp_em','value':'10'},{'name':'i_cp_jb','value':'11'},{'name':'i_cp_nt','value':'12'}]";
This is the desired inserted data looks like:
i_cp_jd i_cp_nm i_cp_tp i_cp_mb i_cp_em i_cp_jb i_cp_nt
xxx 1 2 3 4 5 6
xxx 7 8 9 10 11 12
This is the current loop, but I do not know if this is right:
$arr_cp = //arr_data
foreach($arr_cp as $val_cp){
$dt_cp['i_cp_jd'] = $this->input->post('i_v_id');
//didn't know what to do here
$this->model_vendor->insert_vendor_pic($dt_cp);
}
the the insert method:
function insert_vendor_pic($dt_cp){
$query = $this->db->insert('vendordetail_pic',$dt_cp);
return $query;
}

All you have to do is using json_decode:
$arr_cp = json_decode($yourJsonData, true);

Try this function for prepare/convert your input to matrix:
function prepareData($rawData) {
$rawData = str_replace("'", '"', $rawData);
$data = array();
foreach(json_decode($rawData, true) as $d) {
if (!isset($data[$d['name']])) {
$data[$d['name']] = array();
}
$data[$d['name']][] = $d['value'];
}
$rows = array();
foreach ($data as $col => $values) {
foreach ($values as $i => $v) {
if (!isset($rows[$i])) {
$rows[$i] = array();
}
$rows[$i][$col] = $v;
}
}
return $rows;
}
Convert:
$rawData = "[{'name':'i_cp_nm','value':'1'},{'name':'i_cp_tp','value':'2'},{'name':'i_cp_mb','value':'3'},{'name':'i_cp_em','value':'4'},{'name':'i_cp_jb','value':'5'},{'name':'i_cp_nt','value':'6'},{'name':'i_cp_nm','value':'7'},{'name':'i_cp_tp','value':'8'},{'name':'i_cp_mb','value':'9'},{'name':'i_cp_em','value':'10'},{'name':'i_cp_jb','value':'11'},{'name':'i_cp_nt','value':'12'}]";
print_r(prepareData($rawData));
Output:
Array
(
[0] => Array
(
[i_cp_nm] => 1
[i_cp_tp] => 2
[i_cp_mb] => 3
[i_cp_em] => 4
[i_cp_jb] => 5
[i_cp_nt] => 6
)
[1] => Array
(
[i_cp_nm] => 7
[i_cp_tp] => 8
[i_cp_mb] => 9
[i_cp_em] => 10
[i_cp_jb] => 11
[i_cp_nt] => 12
)
)
Finally you can simple insert this data to DB any way you like.

If you want to do it systematically then you should use an appropriate JSON parser/ deserializer to create an instance of the domain or whatever you are supposed to create from that form data and insert those instances in the DB.

If you want to do it systematically then you should use a appropriate JSON parser/ deserializer to create an instance of the domain or whatever you are supposed to create from that form data and insert that in DB.

The data in the json format, so you have to decode json into array by using
$arr_cp = json_decode($arr_cp, TRUE);
then do $arr_cp into foreach loop
foreach($arr_cp as $val_cp){
$dt_cp['i_cp_jd'] = $this->input->post('i_v_id');
//didn't know what to do here
$this->model_vendor->insert_vendor_pic($dt_cp);
}

Related

PHP - get value from JSON

Before i decode my JSON i get this result:
{
"1":[{"membership_id":1,"group_id":1,"user_id":1},
"2":[{"membership_id":3,"group_id":1,"user_id":2}
}
How would i specify that i want to select the one who has 'user_id' == 2 and return membership_id value?
My attempt, but i get undefined value 'user_id':
$myjson = json_decode($s_o, true);
foreach ($myjson as $key => $value){
if($value['user_id'] == $cid){
$mid = $value['membership_id'];
}
}
echo $mid;
Basically i guess i would first have to select the right object and go through it with the foreach, but here i got a bit lost in the situation.
Use Array-Functions:
$json = '{
"1":[{"membership_id":1,"group_id":1,"user_id":1}],
"2":[{"membership_id":3,"group_id":1,"user_id":2}]
}';
$array = json_decode($json, true);
$searchUserID = 2;
$filteredArray = array_filter($array, function($elem) use ($searchUserID){
return $searchUserID == $elem[0]['user_id'];
});
$mid = array_column(array_shift($filteredArray), 'membership_id')[0];
echo "Membership-ID: ".$mid;
array_filter uses a callback function that iterates over every element of the array. If the callback function returns true, that element is assigned to $filteredArray. No need for a foreach loop that way.
But the return value is the whole array element:
Array
(
[2] => Array
(
[0] => Array
(
[membership_id] => 3
[group_id] => 1
[user_id] => 2
)
)
)
So you have to extract your membership_id.
Read the following line from inside out.
First, we fetch the first entry of the array with array_shift (since we have only one entry, this will be our desired entry).
Array
(
[0] => Array
(
[membership_id] => 3
[group_id] => 1
[user_id] => 2
)
)
We pass this array on to array_column to find the entry in the encapsulated array with the column name membership_id. Since array_column again returns an array,
Array
(
[0] => 3
)
we get the (one and only) entry by adding [0] to the end of this command.
Since the last part is a little complicated, here's a torn apart version of it:
$firstEntryOfFilteredArray = array_shift($filteredArray);
$arrayWithValueOfColumnMembershipID = array_column($firstEntryOfFilteredArray, 'membership_id');
$membership_id = $arryWithValueOfColumnMembershipID[0];
These three lines are concatenated into this:
$mid = array_column(array_shift($filteredArray), 'membership_id')[0];
here's a working example: http://sandbox.onlinephpfunctions.com/code/8fe6ede71ca1e09dc68b2f3bec51743b27bf5303
I'm assuming the JSON actually looks like:
{
"1":[{"membership_id":1,"group_id":1,"user_id":1}],
"2":[{"membership_id":3,"group_id":1,"user_id":2}]
}
Each element of the object is an array for some reason. So you need to index it with $value[0] to access the object contained inside it.
$myjson = json_decode($s_o, true);
foreach ($myjson as $key => $value){
if($value[0]['user_id'] == $cid){
$mid = $value[0]['membership_id'];
break;
}
}
echo $mid;
If the arrays can contain multiple elements, you'll need nested loops.
$myjson = json_decode($s_o, true);
foreach ($myjson as $key => $value){
foreach ($value as $object) {
if($object['user_id'] == $cid){
$mid = $object['membership_id'];
break 2;
}
}
}
echo $mid;
This is a bit speculative, but I think the data is indexed by user ID. If that's the case, it makes the lookup much simpler.
After decoding with $myjson = json_decode($s_o, true);
Just find the record by ID and get the membership_id from the matching row.
$membership_id = reset($myjson['2'])['membership_id'];`
You should probably verify that that ID exists, so maybe something like:
$membership_id = isset($myjson['2']) ? reset($myjson['2'])['membership_id'] : null;
If I'm wrong and the fact that the row numbers match the user_id is just a coincidence, then never mind :)

Iterate over JSON file using PHP [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 5 years ago.
I have a JSON file containing a list of universities around the world. I want to get only specific universities where a field in the array matches what I need to select. The problem I face is that each university has it's own ID number which makes me unable to figure out how to iterate over the Array. The JSON file can be found on this GitHub repo.
The code that makes me convert the JSON file to an array:
<?php
$json = file_get_contents('universities_list.json');
$universityArray = json_decode($json, true);
print_r($universityArray);
?>
And a sample of what I get is:
[2942] => Array
(
[alpha_two_code] => EG
[country] => Egypt
[domain] => aast.edu
[name] => Arab Academy for Science & Technology
[web_page] => http://www.aast.edu/
)
[2943] => Array
(
[alpha_two_code] => EG
[country] => Egypt
[domain] => akhbaracademy.edu.eg
[name] => Akhbar El Yom Academy
[web_page] => http://www.akhbaracademy.edu.eg/
)
What is the best or appropriate way to print out only the universities with alpha_two_code == 'EG' or == 'Egypt' for example?
I read the documentation on foreach loop and the examples as well. But still can't get the logic to get what I mentioned above.
Check this return only a specific country
<?php
$json = file_get_contents('university.json');
$universityArray = json_decode($json, true);
universities= array()
for($i=0; $i< count($universityArray); $i++)
{
if($universityArray[$i]["country"] == "Morocco")
universitises[] = $universityArray[$i];
}
var_dump($universitises);
?>
You can use alpha_two_code as index.
$indexed = [];
foreach($universityArray as $university){
$index = $university['alpha_two_code'];
if(!isset($indexed[$index])){
$indexed[$index] = [];
}
$indexed[$index][] = $university;
}
Now you will have universities seperated by alpha_two_code which you can directly access.
print_r($indexed['EG']);
Now as per the best and appropriate part, you may want to cache $indexed. You can create a directory for universities and save JSON encoded $indexed there.
You need to read the manual.
Try this:
$names = array();
foreach($universityArray as $u) {
if($u['alpha_two_code'] == 'EG' || $u['country'] == 'Egypt'){
$names[] = $u['name'];
}
}
print_r($names);
you can use the array_filter http://php.net/manual/en/function.array-filter.php function here with a callback. You can then use array_column http://php.net/manual/en/function.array-column.phpto grab just the 'name' column.
$json = file_get_contents('https://github.com/Hipo/university-domains-list/blob/master/world_universities_and_domains.json');
$universityArray = json_decode($json, true);
$filterBy = 'EG';
$newArray = array_filter($universityArray, function ($var) use ($filterBy) {
return ($var['alpha_two_code'] == $filterBy);
});
print_r($newArray);
$names = array_column($newArray, 'name');
print_r($names);

PHP Search Multi Dimensional Array [duplicate]

This question already has answers here:
PHP multidimensional array search by value
(23 answers)
Closed 6 years ago.
I have two functions that I am working with. The first one does a database call and grabs two attributes of a user. The UserID and Markup for that user.
/*
Search Markup for a specific QID
*/
function searchMarkup($identifier){
global $markupArray;
if(isset($markupArray)){
foreach($markupArray as $m){
if((string)$key->QID == (string)$identifier){
return $m->markup;
}
}
}
return '';
}
/*
Fetch the markup data for this dashboard
*/
function fetchMarkup(){
global $dashboardID;
global $markupArray;
$objDB = new DB;
$objMarkup = $objDB
-> setStoredProc('FetchMarkup')
-> setParam('dashboardID', $dashboardID)
-> execStoredProc()
-> parseXML();
// Create an array of the markup
if(isset($objMarkup->data)){
$i = 0;
foreach($objMarkup->data as $m){
$markup[$i] = array();
$markup[$i]['QID'] = (string)$m->QID;
$markup[$i]['markup'] = (string)$m->Markup;
$i++;
}
$markupArray = $markup;
}
}
When I run fetchMarkup() and then print out $markupArray, I get the result of:
Array
(
[0] => Array
(
[QID] => Q0002
[markup] => success
)
[1] => Array
(
[QID] => Q101
[markup] => success
)
[2] => Array
(
[QID] => Q200
[markup] => info
)
)
My next step is to be able to search that array by providing a QID and having it return the markup value to me.
I am trying to so something like searchMarkup('Q0002') to have it tell me the result of markup but I am not getting any response.
How could I go about retrieving the value of markup from the array that is created by fetchMarkup() ?
why you are using $key ? which came from no where
foreach($markupArray as $m)
as you can see you alias $m not $key
And $markupArray is an associated array not an object array
So instead of
if((string)$key->QID == (string)$identifier){
return $m->markup;
}
since it is an associated array change it to
if((string)$key['QID'] == (string)$identifier){
return $m['markup'];
}
So your searchMarkup would be like this
function searchMarkup($identifier){
global $markupArray;
if(isset($markupArray)){
foreach($markupArray as $m){
if((string)$m['QID'] == (string)$identifier){
return $m['markup'];
}
}
}
return '';
}
Demo

How to get value of an array element inside two arrays? [duplicate]

This question already has answers here:
How can I access an array/object?
(6 answers)
Closed 6 years ago.
Array
(
[30514] => Array
(
[1001] => Array
(
[Marks_M] => 89
[Marks_C] => 87
)
)
)
This is my multidimensional array.How do i print value of Marks_M using foreach loop.
You can do it this way
echo $outerarray['30514']['1001']['Marks_M'];
$outerarray['30514'] will get you the second Array inside.
echo $outerarray['30514']['1001'] will get you the third Array inside.
Once you get the third one, you can get the value you want using its key eg: ['Marks_M']
You can do something like this
<?php
// consider you have multidimentional array and second level sub array have Marks_M index
$arr = array(
30514=>array(
1001=>array(
'Marks_M'=>89,
'Marks_C'=>87
)
)
);
foreach ($arr as $sub_arr) {
foreach ($sub_arras $subjects) {
if(array_key_exists('Marks_M',$subjects))
{
echo $subjects['Marks_M'];
}
}
}
?>
you can loop an array to reach to the last array in your list and can get the value of Marks_M
<?php
$arr = array(
30514=>array(
1001=>array(
'Marks_M'=>89,
'Marks_C'=>87
)
)
);
foreach ($arr as $value) {
foreach ($value as $val) {
if(array_key_exists('Marks_M',$val))
{
echo $val['Marks_M'];
}
}
}
?>
You can simply do this:
$arr = array('30514'=>array('1001'=>array('Marks_M'=>89,'Marks_C'=>87)));
echo $arr[30514][1001]['Marks_M'];
and if you want to loop then you can use this:
foreach($arr as $array){
foreach($array as $key=>$value){
echo $value['Marks_M'];
}
}

Copy array into another array in PHP

I am trying to copy array into another array in PHP. Then send the response as JSON output. But it copies only the last element in array multiple times. Please let me know where I am going wrong? Any help is appreciated
PHP code
stmt_bind_assoc($stmt, $resultrow);
while ($stmt->fetch()) {
$r[] = $resultrow;
print_r($resultrow);
}
echo json_encode($r);
Output from print_r($resultrow).This is correct. Values in array is different
Array( [a_id] => 1 [b_number] => 10101010 [dateandtime] => 2013-12-25 09:30:00 )
Array( [a_id] => 1 [b_number] => 20202020 [dateandtime] => 2013-12-27 11:40:00 )
Output from json_encode($r).This is incorrect. Values in array is same
[{"a_id":1,"b_number":20202020,"dateandtime":"2013-12-27 11:40:00"},
{"a_id":1,"b_number":20202020,"dateandtime":"2013-12-27 11:40:00"}]
You got the function stmt_bind_assoc from here: http://www.php.net/manual/en/mysqli-stmt.fetch.php#82742
Posted under that OP is:
"...the problem is that the $row returned is reference and not data.
So, when you write $array[] = $row, the $array will be filled up with
the last element of the dataset."
With that user's solution I came up with this to resolve your issue:
// replace your posted code with the following
$r = array();
// loop through all result rows
while ( $stmt->fetch() ) {
$resultrow = array();
foreach( $row as $key=>$value )
$resultrow[ $key ] = $value;
$r[] = $resultrow;
print_r($resultrow);
}
echo json_encode($r);
Next time you get code from a source read the comments about the source.

Categories