I have a script that loops through and retrieves some specified values and adds them to a php array. I then have it return the value to this script:
//Returns the php array to loop through
$test_list= $db->DatabaseRequest($testing);
//Loops through the $test_list array and retrieves a row for each value
foreach ($test_list as $id => $test) {
$getList = $db->getTest($test['id']);
$id_export[] = $getList ;
}
print(json_encode($id_export));
This returns a JSON value of:
[[{"id":1,"amount":2,"type":"0"}], [{"id":2,"amount":25,"type":"0"}]]
This is causing problems when I try to parse the data onto my android App. The result needs to be something like this:
[{"id":1,"amount":2,"type":"0"}, {"id":2,"amount":25,"type":"0"}]
I realize that the loop is adding the array into another array. My question is how can I loop through a php array and put or keep all of those values into an array and output them in the JSON format above?
of course I think $getList contains an array you database's columns,
use
$id_export[] = $getList[0]
Maybe can do some checks to verify if your $getList array is effectively 1 size
$db->getTest() seems to be returning an array of a single object, maybe more, which you are then adding to a new array. Try one of the following:
If there will only ever be one row, just get the 0 index (the simplest):
$id_export[] = $db->getTest($test['id'])[0];
Or get the current array item:
$getList = $db->getTest($test['id']);
$id_export[] = current($getList); //optionally reset()
If there may be more than one row, merge them (probably a better and safer idea regardless):
$getList = $db->getTest($test['id']);
$id_export = array_merge((array)$id_export, $getList);
Related
I am trying to unset a value from test_bots.json and save it back, but somehow the data format is being changed in the process.
test_bots.json contains this JSON array:
["John","Vladimir","Toni","Joshua","Jessica"]
My code looks like this:
$good = 'Toni';
$good_arr = file_get_contents('test_bots.json');
$good_arr = json_decode($good_arr);
if(in_array($good, $good_arr)){
$key = array_search($good, $good_arr);
unset($good_arr[$key]);
$good_arr2 = json_encode($good_arr);
file_put_contents('test_bots.json',$good_arr2);
}
The output that's saved is:
{"0":"John","1":"Vladimir","3":"Joshua","4":"Jessica"}
but I want the output to look like:
["John","Vladimir","Joshua","Jessica"]
I tried to unserialize the array before saving it, but it's not working.
Why is this happening?
In order for json_encode to convert a PHP array with numeric keys to a JSON array rather than a JSON object, the keys must be sequential. (See example #4 in the PHP manual for json_encode.)
You can accomplish this in your code by using array_values, which will reindex the array after you have removed one of the items.
$good_arr2 = json_encode(array_values($good_arr));
Confusing title, the basics are that I'm saving a fully sorted and ordered multidimensional array from a script and into MySQL. I then, on another page, pull it from the database and unserialize it, and then proceed to print it out with this,
$s = "SELECT * FROM gator_historical_data WHERE channelid = '{$chanid}'";
$r = $link->query($s);
$comboarray = array();
while ($row = mysqli_fetch_assoc($r)) {
$comboarray[] = unserialize($row['dataarray']);
}
foreach ($comboarray as $item) {
$desc = $item['content']['description'];
$title = $item['content']['title'];
$datetime = $item['datetime'];
// ... ^^^ problems getting array data
}
The problem is that it doesn't take the full array from MySQL, only the first entry and thus only prints the first 'array'. So where the returned value from dataarray looks like this (var_dump): http://pastebin.com/raw.php?i=Z0jy55sM the data stored into the unserialized $comboarray only looks like this (var_dump): http://pastebin.com/raw.php?i=Ycwwa924
TL;DR: Pulling a serialized multidimensional array from a database, unserializing and it loses all arrays after the first one.
Any ideas what to do?
The string you've got is a serialized string plus something more at the end that is also a serialized string again and again:
a:3:{s:6:"source";s:25:"World news | The Guardian";s:8:"datetime ...
... story01.htm";}}a:3:{s:6:"source";s:16:"BBC News - World";
^^^
This format is not supported by PHP unserialize, it will only unserialize the first chunk and drop everything at the end.
Instead create one array, serialize it and store that result into the database.
Alternatively you can try to recover for the moment by un-chunking the string, however in case the paste was done right, there are more issues. But on the other hand the paste obvious isn't the done fully correct.
I have a question on saving mysqli_fetch_array into multidimensional php array,I have month and amount as data, ex January-12345.0987,February-87654.3456 etc, I am able to get the data from database and able to store it as two different arrays, but I would like to store it in single one and then I want to use that array to send input to highcharts. Can any one please suggest me, below is the code I used for storing the retrieved data into two different arrays
$month=array();
$amount=array();
$i=0;
while($user_data = mysqli_fetch_array($data))
{
//echo 'inside while loop';
$month[$i]=$user_data['month'];
$amount[$i]=$user_data['monthavg'];
$i++;
//$month[$i][$i]=$user_data['month']['monthavg'];
}
I should either use a two dimensional array (the boring way)
$records = mysqli_fetch_all($data);
// Access array of attributes of the first row
var_dump($records[0]);
// Access attribute 'month' of first row
var_dump($records[0]['month']);
// Access attribute 'monthavg' of first row
var_dump($records[0]['monthavg']);
or objects (the cool way):
$records = array();
while($record = mysqli_fetch_object($data))
{
$actualData[] = $record;
}
// Access array of attributes of the first row
var_dump($records[0]);
// Access attribute 'month' of first row
var_dump($records[0]->month);
// Access attribute 'month' of first row
var_dump($records[0]->monthavg);
Then write your JSON or CSV response for your highchart JavaScript app:
$out = fopen('php://output', 'w');
fputcsv($out, $records);
fclose($out);
I recommned you to prepare correct array structure in the php, then use json_encode(). In the javascript use $.getJSON() and load your data. As a result you avoid csv / loading files and parsing it again.
I suck at formatting, maybe I had a bad foundation. I have a json like this
'first_name'=>'steve', 'msg'=>'something here','profile_id'=>1
and I want to push a new item into it, I wrote
$i = array('first_name'=>'steve', 'msg'=>'something here','profile_id'=>1);
$loginId = array($_GET['login_id']);
array_push($i,$loginId);
echo json_encode($i);
The result I got is strange:
$i = array('first_name'=>'steve', 'msg'=>'something here','profile_id'=>1);
$loginId = $_GET['login_id'];
$i['login_id']=$loginId;
echo json_encode($i);
The reason array_push didn't work is because you are treating $i as an array (collection) of objects (arrays), while it is just a key-value list (map).
If the array is like K1=>V1, K2=>V2, use $arr[K3]=V3 to add another pair.
If the array is like [(k1,v1), (k2,v2)], then array_push($arr,(k3,v3));
You are basically taking a value $_GET['login_id'], placing it in an array and trying to push it into an associate array, so you you get a new numeric index 0 holding a nested array, which in turn holds your value.
If you want the entire thing to be treated uniformly as an associative array (or an object once converted to JSON) then you should do something like:
$i = array('first_name'=>'steve', 'msg'=>'something here','profile_id'=>1);
$i['login_id'] = $_GET['login_id'];
echo json_encode($i);
I am trying to change the class of a list of elements based on information in a DB. I figure the easy way was via an array. I build the array on the php side as follows.
$setClassResult = array();
while($row = mysql_fetch_array( $result ))
{
$setClassResult= array_push_assoc($setClassResult, $row['item_id'], $row['parent']);
}
echo json_encode(array($setClassResult));
break;
which give me....
[{"830":"0","734":"830","733":"830","732":"830","735":"830","737":"830","736":"830","738":"830","739":"830","740":"830","741":"830","742":"830","872":"0","869":"872","868":"872","880":"872","964":"872"}]
to decode and change the elements I use.....
$.each(data, function(key, val) {
$("#recordsArray_"+key).toggleClass(val);
alert(key+" "+val);
});
The alert happens once with 0[object,Object] Is this because of the way I created the array? The first thing I notice wrong is the [ and ] around the JSON.
No need to add extra array, try with :
echo json_encode($setClassResult);
Your result is in array of object format:
[{"830":"0","734":"830","733":"830","732":"830","735":"830","737":"830","736":"830","738":"830","739":"830","740":"830","741":"830","742":"830","872":"0","869":"872","868":"872","880":"872","964":"872"}]
So when you iterate, it iterates through array first & says key is 0 & value is an object.so, if you later iterate through value which is an object, you will get it
or as soju if u dont require to store it in array of objects but a single object & iterate once.