I have inbound return data -> http://php.net/manual/en/function.json-decode.php that is in PhP array format. The file data is the same type. It is just $result from the previous cycle.
$result = api_query("mytrades", array("marketid" => $id));
How do I compare $result array with $file array and then over write FILE with $result data?
In other words, FILE and the data it contains is continuously being updated with $result
compare -> overwrite -> repeat at next execution.
I tried array_diff but it does not like my data types and I cannot find a work around.
Note: .db file is empty at first cycle but becomes populated at first write.
sample code with Array to string conversion error:
<?php
$id = 155;
require_once('phpPlay.php');
$result = api_query("mytrades", array("marketid" => $id));
$lines = file("myDB.db");
$arrayDiffresult = array_diff ( $result, $lines);
var_dump($result);
file_put_contents('myDB.db', print_r($result, true));
?>
var_dump($result);
I think, you looking for some serialization, json_encoding for example.
$result = array(
'return' => array(
array(
"tradeid" =>"74038377",
"tradetype" =>"Sell",
"datetime" =>"2014-11-12 16:05:32",
"tradeprice" =>"0.00675000",
"quantity" =>"22.18670000",
"fee" =>"-0.00007488",
"total" =>"0.14976023",
"initiate_ordertype" =>"Buy",
"order_id" =>"197009493",
),
array(
"tradeid" =>"2",
"tradetype" =>"Sell",
"datetime" =>"2014-11-12 16:05:32",
"tradeprice" =>"0.00675000",
"quantity" =>"22.18670000",
"fee" =>"-0.00007488",
"total" =>"0.14976023",
"initiate_ordertype" =>"Buy",
"order_id" =>"2",
)
)
);
function getdiff($new, $old)
{
//implement right logical diff here
$diff = array();
$old_serialized = array();
foreach ($old as $item) {
$old_serialized[] = json_encode($item);
}
foreach ($new as $item) {
if (in_array(json_encode($item), $old_serialized)) {
continue;
}
$diff[] = $item;
}
return $diff;
}
$old = file_exists('1.db') ? json_decode(file_get_contents('1.db'), 1) : array();
$arrayDiffresult = getdiff($result['return'], $old);
file_put_contents('1.db', json_encode($result['return']));
print_r($arrayDiffresult);
Related
I want to separate a PHP array when they have a common prefix.
$data = ['status.1', 'status.2', 'status.3',
'country.244', 'country.24', 'country.845',
'pm.4', 'pm.9', 'pm.6'];
I want each of them in separate variables like $status, $countries, $pms which will contain:
$status = [1,2,3];
$country = [244, 24, 845]
$pms = [4,9,6]
My Current code is taking 1.5 seconds to group them:
$statuses = [];
$countries = [];
$pms = [];
$start = microtime(true);
foreach($data as $item){
if(strpos($item, 'status.') !== false){
$statuses[]= substr($item,7);
}
if(strpos($item, 'country.') !== false){
$countries[]= substr($item,8);
}
if(strpos($item, 'pm.') !== false){
$pms[]= substr($item,3);
}
}
$time_elapsed_secs = microtime(true) - $start;
print_r($time_elapsed_secs);
I want to know if is there any faster way to do this
This will give you results for more dynamic prefixs - first explode with the delimiter and then insert by the key to result array.
For separating the value you can use: extract
Consider the following code:
$data = array('status.1','status.2','status.3', 'country.244', 'country.24', 'country.845', 'pm.4','pm.9', 'pm.6');
$res = array();
foreach($data as $elem) {
list($key,$val) = explode(".", $elem, 2);
$res[$key][] = $val;
}
extract($res); // this will separate to var with the prefix name
echo "Status is: " . print_r($status); // will output array of ["1","2","3"]
This snippet took less the 0.001 second...
Thanks #mickmackusa for the simplification
Add continue to each of the if's, so if it's one of them, it won't then run the other ones... not really needed in the last one as obviously the loops starts again anyway. Should save a tiny bit of time, but doubt it'll be as much as you probably want to save.
foreach($data as $item){
if(strpos($item, 'status.') !== false){
$statuses[]= substr($item,7);
continue;
}
if(strpos($item, 'country.') !== false){
$countries[]= substr($item,8);
continue;
}
if(strpos($item, 'pm.') !== false){
$pms[]= substr($item,3);
continue;
}
}
I'd use explode to split them.
something like this:
$arr = array("status" => [],"country" => [],"pm" => []);
foreach($data as $item){
list($key,$val) = explode(".",$item);
$arr[$key][] = $val;
}
extract($res); // taken from david's answer
and it's a much more readable code (in my opinion)
___ EDIT ____
as #DavidWinder commented, this is both not dynamic and will not result in different variables - look at his answer for the most complete solution for your question
Use Explode. Also is a good way to use $limit param for performance and avoiding wrong behavior on having other '.' in values.
$arr = [];
foreach($data as $item){
list($key,$val) = explode('.', $item, 2);
if (!$key || !$val) continue;
$arr[$key][] = $val;
}
var_dump($arr);
If it was me I would do it like so...
<?php
$data = array ('status.1', 'status.2', 'status.3',
'country.244', 'country.24', 'country.845',
'pm.4', 'pm.9', 'pm.6');
$out = array ();
foreach ( $data AS $value )
{
$value = explode ( '.', $value );
$out[$value[0]][] = $value[1];
}
print_r ( $out );
?>
I'm not sure if this'll boost the performance but you could re-arrange your array in a way that each row has a heading and the corresponding value and then use array_column() to group which data you want.
This is an example of how you could group your data in such a way. (PHP 7.1.25+)
$groupedData = array_map(function($arg) {
[$key, $val] = explode('.', $arg); # for PHP 5.6 < 7.1.25 use list($key, $val) = explode(...)
return array($key => $val);
}, $data);
Then, you can pull out all of the country Id's like so:
$countries = array_column($groupedData, 'country');
Here is a live demo.
You can push data into their respective groups while destructuring. The only iterated function call is explode().
Creating individual variables for each group is a design flaw / mismanagement of array data.
Code: (Demo)
$result = [];
foreach ($data as $value) {
[$prefix, $result[$prefix][]] = explode('.', $value, 2);
}
var_export($result);
Output:
array (
'status' =>
array (
0 => '1',
1 => '2',
2 => '3',
),
'country' =>
array (
0 => '244',
1 => '24',
2 => '845',
),
'pm' =>
array (
0 => '4',
1 => '9',
2 => '6',
),
)
Use sscanf() if you want to directly/explicitly cast the numeric values as integers. Demo
I want to separate a PHP array when they have a common prefix.
$data = ['status.1', 'status.2', 'status.3',
'country.244', 'country.24', 'country.845',
'pm.4', 'pm.9', 'pm.6'];
I want each of them in separate variables like $status, $countries, $pms which will contain:
$status = [1,2,3];
$country = [244, 24, 845]
$pms = [4,9,6]
My Current code is taking 1.5 seconds to group them:
$statuses = [];
$countries = [];
$pms = [];
$start = microtime(true);
foreach($data as $item){
if(strpos($item, 'status.') !== false){
$statuses[]= substr($item,7);
}
if(strpos($item, 'country.') !== false){
$countries[]= substr($item,8);
}
if(strpos($item, 'pm.') !== false){
$pms[]= substr($item,3);
}
}
$time_elapsed_secs = microtime(true) - $start;
print_r($time_elapsed_secs);
I want to know if is there any faster way to do this
This will give you results for more dynamic prefixs - first explode with the delimiter and then insert by the key to result array.
For separating the value you can use: extract
Consider the following code:
$data = array('status.1','status.2','status.3', 'country.244', 'country.24', 'country.845', 'pm.4','pm.9', 'pm.6');
$res = array();
foreach($data as $elem) {
list($key,$val) = explode(".", $elem, 2);
$res[$key][] = $val;
}
extract($res); // this will separate to var with the prefix name
echo "Status is: " . print_r($status); // will output array of ["1","2","3"]
This snippet took less the 0.001 second...
Thanks #mickmackusa for the simplification
Add continue to each of the if's, so if it's one of them, it won't then run the other ones... not really needed in the last one as obviously the loops starts again anyway. Should save a tiny bit of time, but doubt it'll be as much as you probably want to save.
foreach($data as $item){
if(strpos($item, 'status.') !== false){
$statuses[]= substr($item,7);
continue;
}
if(strpos($item, 'country.') !== false){
$countries[]= substr($item,8);
continue;
}
if(strpos($item, 'pm.') !== false){
$pms[]= substr($item,3);
continue;
}
}
I'd use explode to split them.
something like this:
$arr = array("status" => [],"country" => [],"pm" => []);
foreach($data as $item){
list($key,$val) = explode(".",$item);
$arr[$key][] = $val;
}
extract($res); // taken from david's answer
and it's a much more readable code (in my opinion)
___ EDIT ____
as #DavidWinder commented, this is both not dynamic and will not result in different variables - look at his answer for the most complete solution for your question
Use Explode. Also is a good way to use $limit param for performance and avoiding wrong behavior on having other '.' in values.
$arr = [];
foreach($data as $item){
list($key,$val) = explode('.', $item, 2);
if (!$key || !$val) continue;
$arr[$key][] = $val;
}
var_dump($arr);
If it was me I would do it like so...
<?php
$data = array ('status.1', 'status.2', 'status.3',
'country.244', 'country.24', 'country.845',
'pm.4', 'pm.9', 'pm.6');
$out = array ();
foreach ( $data AS $value )
{
$value = explode ( '.', $value );
$out[$value[0]][] = $value[1];
}
print_r ( $out );
?>
I'm not sure if this'll boost the performance but you could re-arrange your array in a way that each row has a heading and the corresponding value and then use array_column() to group which data you want.
This is an example of how you could group your data in such a way. (PHP 7.1.25+)
$groupedData = array_map(function($arg) {
[$key, $val] = explode('.', $arg); # for PHP 5.6 < 7.1.25 use list($key, $val) = explode(...)
return array($key => $val);
}, $data);
Then, you can pull out all of the country Id's like so:
$countries = array_column($groupedData, 'country');
Here is a live demo.
You can push data into their respective groups while destructuring. The only iterated function call is explode().
Creating individual variables for each group is a design flaw / mismanagement of array data.
Code: (Demo)
$result = [];
foreach ($data as $value) {
[$prefix, $result[$prefix][]] = explode('.', $value, 2);
}
var_export($result);
Output:
array (
'status' =>
array (
0 => '1',
1 => '2',
2 => '3',
),
'country' =>
array (
0 => '244',
1 => '24',
2 => '845',
),
'pm' =>
array (
0 => '4',
1 => '9',
2 => '6',
),
)
Use sscanf() if you want to directly/explicitly cast the numeric values as integers. Demo
I'm a newbie here so please be with. I'm pretty sure that my code and syntax is correct.
This is my json file
{"data":
[
{"label":"Signed-in Client","value":2
}
]
}
This is my php code
<?php
$conn=mysqli_connect("localhost", "root","","something");
$res1 = mysqli_query($conn, "SELECT * FROM tbl_pet_owner ORDER BY pet_owner_id");
$max1 = mysqli_num_rows($res1);
$jsonString = file_get_contents('data.json');
$data1 = json_decode($jsonString, true);
foreach ($data1['data'] as $key )
{
if ($key[0]['label'] == "Signed-in Client")
{
$data1['value'] = $max1;
}
}
$newJsonString = json_encode($data1);
file_put_contents('data.json', $newJsonString);
?>
but when I refresh, it doesn't update with the max count of my query. I hope you'd help me. This is for my thesis
It seems to me that the problem is connected with the way how you traverse the data.
For example in foreach ($data1['data'] as $key ), $key is already an associative array (e.g., array("label" => "Signed-in Client", "value" => 2)), so instead of $key[0]['label'], one should use just $key['label'].
Also, when you want to modify the 'value', one has to access the same associative array, not the original variable $data1.
One way to achieve this would be as shown below. In that example the array $data1['data'] is traversed using references (&$key). Note that one should then unset this variable after the foreach block to break its association with the last element of the array being traversed.
<?php
$max1 = 100;//just an example
$jsonString = file_get_contents('data.json');
$data1 = json_decode($jsonString, true);
foreach ($data1['data'] as &$key )
{
print_r($key);
if($key['label'] == "Signed-in Client")
{
$key['value'] = $max1;
}
}
unset($key);
print_r($data1);
/* gives:
Array
(
[data] => Array
(
[0] => Array
(
[label] => Signed-in Client
[value] => 100
)
)
)
*/
//$newJsonString = json_encode($data1);
//file_put_contents('data.json', $newJsonString);
?>
I know that this is asked few times here but there is an advanced problem.
I got an array $data and I need to got this structure when foreach
$data[0] => [
'value1' => string(x) "some data",
'value2' => string(x) "some other data"
];
$data[1] => ... ...
I know that can't execute array_push with array keys also tried code bellow but I got two big arrays. I just need one big array with small sub arrays
My Code
$authors['email'] = array();
$authors['name'] = array();
foreach (json_decode($response)->response->docs AS $docs)
{
$articleAuthors = explode(', ', $docs->authors);
$i=0;
foreach ($docs->email as $email) {
array_push($authors['email'], $email);
array_push($authors['name'], $articleAuthors[$i]);
++$i;
}
}
Try this, to get one array with little subarrays
$authors = array();
#...
foreach($docs->email as $email){
array_push($authors, array('email'=>$email,'name'=>$articleAuthors[$i]));
++$i;
}
#...
I just find solution, code above is makeing two big arrays and just added line bellow.
$authors['email'] = array();
$authors['name'] = array();
foreach (json_decode($response)->response->docs AS $docs)
{
$articleAuthors = explode(', ', $docs->authors);
$i=0;
foreach ($docs->email as $email) {
array_push($authors['email'], $email);
array_push($authors['name'], $articleAuthors[$i]);
++$i;
}
}
$data = array_combine($authors['name'], $authors['email']);
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
}