How to add sub array in a JSON file? - arrays

I have a result json file namely result.json and I would to insert another sub array in total and rows.
This is my JSON File
{"total":"9","rows":[
{"id":"16","firstname":"Melanie","lastname":"Toledo","phone":"091919191","email":"test#gmail.com"}, {"id":"29","firstname":"x","lastname":"x","phone":"1","email":"test#gmail.com"}, {"id":"30","firstname":"y","lastname":"y","phone":"2","email":"test#gmail.vp"}, {"id":"31","firstname":"xxx","lastname":"xxxx","phone":"12345","email":"test#gmail.com"}, {"id":"33","firstname":"xy","lastname":"xy","phone":"1","email":"test#gmail.com"}, {"id":"34","firstname":"yyy","lastname":"yyy","phone":"2","email":"test#gmail.com"}, {"id":"35","firstname":"n","lastname":"n","phone":"1","email":"test#gmail.com"}, {"id":"36","firstname":"q","lastname":"q","phone":"1","email":"x#g.com"}, {"id":"37","firstname":"","lastname":"","phone":"","email":""}
]
}
Here is my code
<?php
$current_data = file_get_contents('result.json');
$array_data = json_decode($current_data, true);
$extra['rows'] = array (
'id' => '101',
'firstname' => 'marlon',
'lastname' => 'berces',
'phone' => '12',
'email' => 'test#gmail.com'
);
$array_data[] = $extra;
$final_data = json_encode($array_data);
file_put_contents('result.json',$final_data);
?>

If I understood your question correctly, you will need to add the new row in the current list of rows, and after that, you have to update the sum, as this is all static data that came from the file.
<?php
// Read json
$current_data = file_get_contents('result.json');
$array_data = json_decode($current_data, true);
// New row
$extra = array(
'id' => '101',
'firstname' => 'marlon',
'lastname' => 'berces',
'phone' => '12',
'email' => 'test#gmail.com'
);
// Add the new row
$array_data['rows'][] = $extra;
// Update the sum
$array_data['total'] = count($array_data['rows']);
// Write json
$final_data = json_encode($array_data);
file_put_contents('result.json',$final_data);
?>

you can do it by convert it an array then use array_push for add new value agani convert to json...

I think what you are looking for is the Array.prototype.push() method(In JavaScript). Or if you are using PHP, then array_push().
The push()/array_push() method adds one or more elements to the end of an array and returns the new length of the array.

Related

Remove array key from array in cakephp

print array
array(
'Order' => array(
'id' => '1',
'base_price' => '65',
'min_price' => '95',
)
)
Is it possible to remove the key('Order') when you retrieving data? if Not how can I use array_shift or end in one line and to prevent below error?
I am getting this error Only variables should be passed by reference when I remove the key from array.
$orders = array_shift or end ($this->Order->read(null, $id));
debug($orders);
You want only id from it then following code will help you
$arrOrderId=Set::extract("/Order/id",$data);
here $data is your array from where you want to delete this "Order" key.
You will get following array when you do debug($arrOrderId);
[0]=>1
if you want base_price then write following code
$arrOrderId=Set::extract("/Order/base_price",$data);
You can use Set functions for manipulating arrays:
Set::extract($array, 'Order');
Will output:
array(
'id' => '1',
'base_price' => '65',
'min_price' => '95',
)
If you need to do this on every output, you can override afterFind() method on your model.
Please see the docs:
http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::extract
http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::classicExtract

CakePHP UpdateAll Only Updating Last Entered Data

I have built an invoice system in my new CakePHP site and I am currently trying to build a function that will let me save the re-edited information back into the same records.
Below is the section of code I am working on,
$InvoiceDataVar = $this->data['Invoicedata'];
foreach ($InvoiceDataVar as $DataKey => $DataValue) {
$UpdateWork = $InvoiceDataVar[$DataKey]['workdes'];
debug($UpdateWork);
$this->Invoicedata->updateAll(
array('Invoicedata.workdes' => "'$UpdateWork'"),
array('Invoicedata.invoicejoblists_id' => $InvoiceID)
);
}
This is work $this->data holds,
'Invoicedata' => array(
(int) 0 => array(
'workdes' => 'test new update 1',
'price' => '500.00'
),
(int) 1 => array(
'workdes' => 'test new update 2',
'price' => '501.00'
),
(int) 2 => array(
'workdes' => 'test new update 3',
'price' => '503.00'
),
(int) 3 => array(
'workdes' => 'test new update 4',
'price' => '504.00'
),
(int) 4 => array(
'workdes' => 'test new update 5',
'price' => '505.00'
),
(int) 5 => array(
'workdes' => 'test new update 6',
'price' => '999.99'
)
)
These are of course just test data, but unless I am not understanding the UpdateAll function documentation which I have gone over many times, all this will do is update all the six fields with the last test input. Right now all the fields for the workdes contain, 'test new update 6'.
I should also say that there might not be all ways be six fields, there will always be at lest one, with a max (at this time) of 6 inputs to update.
I was thinking about loading the 'ID of the invoicedata table, which is an auto count number, where as the joblist_id is the same id in all the the fields being updated? This is my current line of thinking....
Any Help is most welcome.
Glenn.
It seems you are working with CakePHP 1.3
To udpate many records at once there is a shortcut way shown in documentation
First you need to include ids of Invoicedata model in the post data
'Invoicedata' => array(
(int) 0 => array(
'id' => 23, // include id of the record
'workdes' => 'test new update 1',
'price' => '500.00'
),
// other records
)
// then call save all function
$this->Invoicedata->saveAll($this->data['Invoicedata']);
Please, check: updateAll documentation you can see, that first parameter is $fields, which fields you wanto to update and their appropriate values, and second parameter is $conditions some restrictions which define scope of rows which will be changed. You have empty $conditions, so, all rows will be updated. Last values ( here you need to check source code of DataSource update method), but think that it produce some think like
UPDATE invoicedatas SET workdes = value1, price = value2, workdes = value3, price = value4 and etc
so last values will be used.
Your data arrays should contain id attribute, to update right records and for this you should use save or saveAll methods of Invoicedata model.

Cakephp to Google Chart

In my controller I create the array to be charted
function chart() {
$results = $this->Visit->query(
"SELECT date(visits.created) as visit_date,
Count(visits.id) AS count_visits
FROM visits
GROUP BY date(visits.created)"
);
foreach($results AS $result) {
$row = array(
$result[0]['visit_date'],
$result[0]['count_visits']
);
$chartData[] = json_encode($row);
}
pr($chartData);
}
pr($chartData) gives following array
Array
(
[0] => ["2012-07-11","5"]
[1] => ["2012-07-13","1"]
[2] => ["2012-07-14","1"]
)
in chart view i have
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create the data table.
var data = google.visualization.arrayToDataTable($chartData);
var options = {
title: 'Visits by Date',
hAxis: {title: 'Date', titleTextStyle: {color: 'black'}}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
but this doesn't get me a chart .. no errors ... just no chart ..
if I manually type in an array to test my view, it works fine ... eg if i replace ..
var data = google.visualization.arrayToDataTable($chartData);
with the following format from Google Chart example it generates a nice column chart
var data = google.visualization.arrayToDataTable([
['Date', 'Count'],
['2012-07-11', 5],
['2012-07-13', 1],
['2012-07-14', 1]
]);
couple of questions:
- how do i get the header titles in the var data array?
- do double quotes or single quotes in array make a difference?
- am i passing the array $chartData from php to Google chart javascript correctly?
- the Google example has '[]' around the array, how do i get those around my array too?
(bwt, i know all about cakephp's Find(all) but I just got lost in documentation about how to get what i wanted and sql was much easier )
you are using json_encode in your controller, but in your view you are using -
google.visualization.arrayToDataTable($chartData);
json_encode creates json object, not and javascript array.
using json_encode in your controller function chart() try:
$chartData['cols'] = array(
array('id' => 'visit_date', 'label' => 'Visit date', 'type' => 'date'),
array('id' => 'count_visits', 'label' => 'Count', 'type' => 'number')
);
foreach($results AS $result) {
$time = strtotime($result[0]['visit_date']);
$dateJs = 'Date('.date("Y", $time).', '.(date('n', $time) - 1).', '.date('j', $time).')';
$row = array(
'c' => array(
array('v' => $dateJs),
array('v' => $result[0]['count_visits']),
)
);
$chartData['rows'][] = $row;
}
//make the data available for view
$this->set('chartData', json_encode($chartData);
in your view use :
var data = new google.visualization.DataTable($chartData);

php multidimensional array as name value pair

For ecommerce, that expected name value pair I have the following approved code:
function create_example_purchase() {
set_credentials();
$purchase = array(
'name' => 'Digital Good Purchase Example',
'description' => 'Example Digital Good Purchase',
'amount' => '12.00', // sum of all item_amount
'items' => array(
array( // First item
'item_name' => 'First item name',
'item_description' => 'a description of the 1st item',
'item_amount' => '6.00',
'item_tax' => '0.00',
'item_quantity' => 1,
'item_number' => 'XF100',
),
array( // Second item
'item_name' => 'Second Item',
'item_description' => 'a description of the 2nd item',
'item_amount' => '3.00',
'item_tax' => '0.00',
'item_quantity' => 2,
'item_number' => 'XJ100',
),
)
);
return new Purchase( $purchase);
}
I would like to get $items Array inside associative $purchase array dynamically from shipping cart.
Is there a way to generate exactly the same output above?
My dirty solution, to write $purchase array as string inclusive the generated $items array in a file and include it
later in the called script.
Help appreciated.
$itemsArray = function_that_returns_your_2d_item_array();
$purchase['items'] = $itemsArray;
or if the function_that_returns_your_2d_item_array() returns a 2d array indexed by 'items' you could do:
$purchase = array_merge($purchase, $itemsArray);

Is the db in $this->db->last_insert() the class or the constant?

Since I am using 2 databases I have 2 separate config setups in config/database.php and load them in the Model's constructor with
$this->DB1 = $this->load->database('default', TRUE);
$this->DB2 = $this->load->database('reserve', TRUE);
I need to retrieve the id of the last inserted record and have used $this->db->last_insert();
and $this->DB2->last_insert();
but neither is working.
My insert query works fine and is
$insArray = array(
'propNumber' => $prp,
'fname' => $fname,
'lname' => $lname,
'unit' => $unit,
'email' => $email,
'NOC' => 0
);
$this->DB2->insert('users', $insArray);
$last_id = $this->db->last_insert();
$_SESSION['userID'] = $last_id;
return 'valid';
http://php.net/manual/en/function.mysql-insert-id.php
$last_id = $this->DB2->mysql_insert_id();

Resources