Using Laravel 5.2 and I want to import a CSV and store the records in the database. Name, Surname and Contact Number will be core fields and anything else will just be additional data that I want to store as JSON in an additional info field
example
* | name | surname | contact_number | gender | race |"
* | piet | pokol | 0111111111 | male | race |"
will be stored like so:
* ['name'=>'piet','surname'=>'pokol', 'contact_number'=>'0111111111', 'additional_data'=>'{gender:"male", race:"green"}']
My question is,is it possible to combine an array with JSON array like this?
So far I have it working to make a traditional array with this code
foreach ($reader as $index => $row) {
if ($index === 0) {
$headers = $row;
} else {
$data = array_combine($headers, $row);
$array = array_merge($data, ['client_id' => $client_id, 'list_id' => $list_id]);
Customer::create($array);
}
}
But I need to JSON encode all the field that are not core fields and then add them to the array.
Any body have any advice on this?
Check the below code, it might help you. You can use result array to store in database.
<?php
$data = array(
'name'=> "My Name",
'surname'=> 'My Surname',
'contact_number'=> '0987456321',
'age'=> '38',
'gender'=> 'female',
'address'=> 'NewYork, USA',
);
$core = array('name','surname','contact_number');
$result = array();
$additional = array();
foreach($data as $key => $val) {
if(in_array($key, $core)) {
$result[$key] = $val;
} else {
$additional[$key]= $val;
}
}
if(count($additional)) {
$result['additional'] = json_encode($additional);
}
echo "<pre>";
print_r($result);
?>
Related
I have 3 tables, the first one is table name Post, the second is comment, and third is defineComment. I want to show all 3 tables, but my code is too long. Could you please advice me?
$r = $this->w->listwall();
if($r)
{
foreach($r as $key)
{
// load comment to view data
$pc['pc_comment'] = $this->w->get_comments($key['p_id']);
$data['wall'][] = [
'u_id'=>$key['u_id'],
'p_id'=>$key['p_id'],
'u_fname'=>$key['u_fname'],
'u_lname'=>$key['u_lname'],
'p_text'=>$key['p_text'],
'p_date'=>$key['p_date'],
'u_pf' =>$this->pf->getprofile($key['u_id']),
'p_img'=>$this->w->getimg($key['p_id']),
'cover'=>$this->w->getcoverimg($key['p_id']),
'bgpf' =>$this->w->getbgimg($key['p_id']),
'p_link'=>$key['p_link'],
'pc_comment'=>$this->w->get_comments($key['p_id']),
'pc_count'=>$this->w->get_count_comment($key['p_id']),
'pc'=>$this->load->view('wall/v_comment_wall', $pc, TRUE),
'p_like'=>$this->w->get_list_like($key['p_id']),
'count_like'=>$this->w->count_like_post($key['p_id'])
];
}
$data['pf'] = $this->pf->getprofile(uid());
//$data['edittext'] =
//if(count($data) >= 1){
$this->load->view('wall/v_wall',$data);
I also try the code below but It didn't work.
$r = $this->w->listwall();
foreach ($r as $key => $value) {
$data[] = array($key => $value, $this->w->get_comments($value['p_id']));
}
I'm trying to export the MySQL table below:
id, asof, value
abc, 2013-06-30, 36000000
abc, 2013-12-31, 48000000
abc, 2014-01-31, 51000000
abc, 2014-02-28, 56000000
xyz, 2013-06-30, 26000000
xyz, 2013-12-31, 33000000
xyz, 2014-01-31, 33000000
xyz, 2014-02-28, 36000000
into the following json format for use in the nvd3.js charts:
[
{
"key" : "abc" ,
"values" : [ [ 2013-06-30, 36000000] , [ 2013-12-31, 48000000] , [ 2014-01-31, 51000000] , [ 2014-02-28, 56000000]
},
{
"key" : "xyz" ,
"values" : [ [ 2013-06-30, 26000000] , [ 2013-12-31, 33000000] , [ 2014-01-31, 33000000] , [ 2014-02-28, 36000000]
}
]
I'm sure this is a newbie question but I'm struggling with it. Any guidance would be much appreciated!
Edit:
I've currently been trying to use an array and while statement but have not been able to figure out how to modify the array to so that it can output to the correct json format.
$query= mysqli_query($db,"SELECT id, asof, value
FROM table;"
);
if ( ! $query) {
echo mysqli_error();
die;
}
$rows = array();
while($r = mysqli_fetch_assoc($query)) {
$rows[] = $r;
}
print json_encode($rows);
Probably the most straightforward way of doing this is simply creating a multidimensional array, filling it with data obtained from database and then using json_encode to create a JSON string, which is then sent to the client.
Here is a simple example of a function which will accept an array of items and return a JSON string in the expected format. For simplicity, it is assumed that data was is a 2D array with three columns, but you should modify it to use the format returned by a database query.
function convert($data) {
$intermediate = array();
// This intermediate steps is used just to group all rows with
// the same key
foreach($data as $item) {
list($key, $date, $value) = $item;
$intermediate[$key][] = array($date, $value);
}
$output = array();
foreach($intermediate as $key => $values) {
$output[] = array(
'key' => $key,
'values' => $values
);
}
return $output;
}
Since you're getting data from database, variable $item inside the first foreach statement might actually be an associate array, so you'll have to write something like $item['key'] to get data for columns in the current row.
If you want to use mysqli_fetch_assoc, then you might try calling the function convert in the following way:
$conn = mysqli_connect('', '', '')
$query = 'SQL you wish to execute'
$result = mysqli_query($conn, $query)
if($result) {
$jsonData = convert($result);
}
However, function itself needs a little bit changing
function convert($result) {
$intermediate = array();
while($item = mysqli_fetch_assoc($result)) {
$key = $item['id'];
$date = $item['asof'];
$value = $item['value'];
$intermediate[$key][] = array($date, $value);
}
// The rest of the function stays the same
}
I want to output the result of a query so that the format is the same as:
$links = array(
'Link 1' => '/link1',
'Link 2' => '/link2'
);
So the query is
$query = "SELECT * FROM link";
$result = mysql_query($query, $connection) or die(mysql_error());
$row = mysql_fetch_assoc($result)
The field that need to be output are:
$row['link_title'] and $row['url']
This is probably a bit more complex then desired or necessary but would this work for you:
$a = 0;
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $k => $v) {
// Assumes table column name is 'link_title' for the link title
if ($k == 'link_title') {$title[$a] = $v;}
// Assumes table column name is 'url' for the URL
if ($k == 'url') {$url[$a] = $v;}
}
$a++;
}
$i = 0;
foreach ($title as $t) {
$links[$t] = $url[$i];
$i++;
}
print_r($links);
As #Class stated, if the link_title's never repeat than you could do something like this:
while ($row = mysql_fetch_assoc($result)) {
$array[$row['link_title']] = $row['url'];
}
Since the link_title's were unique both processes output:
Array (
[Moxiecode] => moxiecode.com
[Freshmeat] => freshmeat.com
)
Database table + contents:
id | link_title | url |
---+------------+---------------|
1 | Moxiecode | moxiecode.com |
---+------------+---------------|
2 | Freshmeat | freshmeat.com |
Are you looking for something like this:
$links = array();
while(foo){
$links[$row['link_title']] = $row['url'];
}
OR you can use which might cause overriding if the title is the same like in the example above
$link = array();
$title = array()
while($row = mysql_fetch_assoc($result)){
array_push($title, $row['link_title']);
array_push($link, $row['url']);
}
$links = array_combine($title, $link);
Also use PDO or mysqli functions mysql is deprecated. Here's a tutorial for PDO
EDIT: Example: http://codepad.viper-7.com/uKIMgp I don't know how to create a example with a db but its close enough.
You want to echo out the structure of the array?
foreach ($Array AS $Values => $Keys)
{
echo "Array Key: <b>". $Keys ."</b> Array Value:<b>". $Values ."</b>";
}
This will echo out the structure of your exampled array
I have such table:
id | name | link
---+--------------------------------------+---------------
1 |SAsasasdsa,Главная страница,Main page | addsad
I want to get array like that:
$arr = array('az'=>'SAsasasdsa','ru'=>'Главная страница','en'=>'Main page');
TRY
$qry = mysql_query('SELECT * FROM table');
//for multiple rows
$row = mysql_fetch_assoc($qry)) { $input[] = $row['name'] }
$key = array('az', 'ru', 'en');
foreach($input as $val) {
$output[] = array_combine($key,explode(',',$val));
}
echo "<pre>"; print_r($output);
Reference
array_combine
code;
$all_tags = array();
while ($row = mysql_fetch_assoc($result)) {
$all_tags = array_merge($all_tags, explode(' ', $row['title']));
}
$all_tags = array_count_values($all_tags);
echo "<pre>";
arsort($all_tags);
foreach ($all_tags as $key => $val) {
echo "$key = $val\n";
}
output;
fuups! = 7
401 = 5
Authorization = 5
Required = 5
, = 3
izle = 3
Error = 2
Server = 2
Internal = 2
500 = 2
Full = 1
MegaSinema.net = 1
Sinema = 1
Bad = 1
Request = 1
Film = 1
400 = 1
all i wanna do is merge 'keys' with same integer 'value'. example;
401 = 5
Authorization = 5
Required = 5
to
401 Authorization Required = 5
i don't know how could i do it. i tried a bunch of ways but i never let it work. thank you.
I misunderstood you in the beginning.
I think you could just save the objects in an array and implode them if needed.
$out = array();
foreach($array as $key=>$value)
if(array_key_exists($value, $out))
$out[$value][] = $key;
else
$out[$value] = array($key);
// Then you could do
echo implode(" ", $out[5]); // Should output "401 Authorization Required"
Working example at http://codepad.org/MgLKXA75
Another option is to directly append it and trim the "extra" space at the end.
$out = array();
foreach($array as $key=>$value)
if(array_key_exists($value, $out))
$out[$value] .= $key . ' ';
else
$out[$value] = $key . ' ';
// Then you could do
echo trim($out[5]); // Should output "401 Authorization Required"
Try this
<?php
$data = array('fuups!' => '7','401' => '5','Authorization' => '5','Required' => '5',',' => '3','izle' => '3','Error' => '2','Server' => '2','Internal' => '2','500' => '2','Full' => '1','MegaSinema.net' => '1','Sinema' => '1','Bad' => '1','Request' => '1','Film' => '1','400' => '1');
$rows = array();
$values = array_values($data);
asort($values);
$highestVal = $values[0];
for ($i = 0; $i <= $highestVal; $i++) {
foreach ($data as $key => $value) {
if ($i == $value) {
$rows[$i] = $rows[$i] . " {$key}";
}
}
}
?>
Working Example XD http://codepad.org/x9uHs1sp
EDIT----
To echo all keys, just replace var_dump($rows) with:
foreach ($rows as $key) {
echo "{$key}<br />";
}
I'm not familiar with PHP, but I think you can try to create a hash table to handle this.
For example, if you insert above 3 items into the hash table and use '5' as the key, the first item can be inserted correctly, and the other two should throw exceptions. You can catch the exception since it's excepted and append the values to the value of the first item. So the item in you hash table should be like:
key: 5
value: 401 Authorization Required
But you should make sure about the orders in the value.
Just my 2 cents, good luck!
Update:
If throwing exception is not acceptable, you can look-up a key in the hash table first, if the key doesn't exist then insert the key and value, if it already exists then append the value to existing item value.