I have two rows (longitude and latitude) in my MySQL table. I want to get the two rows into a 2-dimensional array such that when the values (longitude and latitude) change in the database the values will be added to the array. Not that the values will be updated.
while($mRow = $resultMarker->fetch_assoc()){
$myArrayForMarkers [] = $mRow['latitude'];
$myArrayForMarkers [] = $mRow['longitude'];
}
print_r($myArrayForMarkers);
The issue I have in the code above is that instead of the new values to be added from the database to the array, the values in the array are being updated. Any help would be appreciated.
As I said in the comments, the wording of your question makes little sens. For example, I don't undurstand what you mean by 'Not that the values will be updated.' nor how your array being 'updated' is different to 'the values will be added to the array'.
Please clarify your question, especially if my answer doesn't solve it so that those who will eventually come here while looking after a solution can understand if your issue is the same than theirs.
I get that you try to craft a 2-dimension array.
The code you provided produces 1-dimension arrays.
If you want to store your datas in a 2-dimension array, I only see two solutions :
Either your main array has two subarrays, each containing one type of data :
while ($mRow = $resultMarker->fetch_assoc()) {
$myArrayForMarkers['latitude'][] = $mRow['latitude'];
$myArrayForMarkers['longitude'][] = $mRow['longitude'];
}
or en
each entry of your array itself contains both information :
while ($mRow = $resultMarker->fetch_assoc()) {
$myArrayForMarkers[] = array('latitude' => $mRow['latitude'], 'longitude' => $mRow['longitude']);
}
That's the most I can do right now, since I don't understand the rest of your question.
Related
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);
$myArray = array();
for($i=0;i<2;$i++){
..
.. //get the content logic here
assign it to array
$myArray["item"]["content"] = $item_content;
}
echo json_encode($myArray);
The above code produced this result:
Which has an error because I didn't merge them.
I tried to merge like this:
$finalJson = array_merge($finalJson, $myArray);
but the output of echo $finalJson is one object instead of 3.
Update:
Your real problem is down to your use of array_merge on an associative array. The behaviour of array_merge is to reassign duplicate keys if they are associative (cf the docs):
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
And because $myArray is clearly using strings as keys, the values in $finalJson are being reassigned. What you need to do is either create unique keys on each iteration, or simply push the values of $myArray onto a numerically indexed $finalJson array (like I showed in my original answer below)
The problem is simply this:
$myArray["item"]["content"] = $item_content;
it's inside the loop, each time reassigning the value of $myArray["item"]["content"], and not adding it to the array. I suspect that what you wanted to do is add this at the bottom of your loop (for each new value of $myArray):
$finalJson[] = $myArray;
Then, on the next iteration, $myArray will be reassigned, and its new value will be appended to the $finalJson variable.
i have a tricky problem.
What i do.
I generate from the System Tables of Databases (DEV ,Test Prod setup) information for Tables, Vies trigger … with PHP and compare the results ti see teh differences with JavaScript.
Also I have a Documentation DB for additional business information which was installed only once on TEST DB.
Therfore I need to connect all four environments to get the data.
I use
if ($flag === 'i')
for information DB and
elseif ($flag === 's')
for system db‘s.
Result is $row_array and $info_array which must be combined and sendet back to Javascript.
$json_response = array_merge($rinfo, $rsql );
echo json_encode($json_response, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
I try this merge in a different positions in the program.
First time in
elseif ($flag === 'i') {
result json:
[
{
"0": "ACT",……….
} ][ ]
second time after } //ifelse return also 2 arrays
[{"0":"ACT","1":"Tabelle Akten","2":"hh","3":null,"4":null,"5":"UCC","6":"Y","7":"Reload Data in Test","8":"y","9":"delete all older tha","10":"n","11":" ","12":"y","13":" ","14":"o","15":"y","16":"o","17":"y","18":"y","19":"Diese tabelle speichert die Acten Verweise","20":"Gert Dorn","21":1570254359,"TDESCRIPTION":"n","TTYPE":" ","TREC_ESTIM":"y","TREC_GROWTH":" ","TDOMAIN":"o","TREL_TYPE":"y","TREL_RULES":"o","THOUSEKEEPING":"y","THOUSE_RULES":"y","TCID":"Diese tabelle speichert die Acten Verweise","TCID_RULES":"Gert Dorn","TUSE_UCC":1570254359,"TUSE_DWH":"","TUSE_ODS":"","TUSE_CWF":"","TUSE_IWF":"","TUSE_OWF":"","TUSE_DEP_MANAGER":"","TENTITY_DESCRIPTION":"","TOWNER":""
,"TTIMESTAMP":""**}][{**"0":"ACT","1":"DB2INST1"
,"2":"USERSPACE1","3":null,"4":"2018-11-21 16:43:20.066567","5":"2018-12-07 10:12:10.255759","6":null,"7":"2020-03-26","8":"2018-11-21 16:43:20.343258","9":3,"NAME":"ACT","CREATOR":"DB2INST1","TBSPACE":"USERSPACE1","REMARKS":"","CTIME":"2018-11-21 16:43:20.066567","STATS_TIME":"2018-12-07 10:12:10.255759","STATISTICS_PROFILE":"","LASTUSED":"2020-03-26","ALTER_TIME":"2018-11-21 16:43:20.343258","COLCOUNT":3}]
The program code and result you can download at
http://dmdg.io/dmdg.zip
Hope you can help Kind regards gert
Did you consider using array_push?
array_push is always preferred than myArray[] = $value
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 problem, to obtain the values of the table wp_postmeta and meta_key "construccion_value", the results are serialized. This is the code I use.
$datos = get_post_custom_values('construccion_value');
$datos= maybe_unserialize($datos);
print_r($datos);
When do I print these results appear
Array ( [0] => a:2:{i:0;s:0:"aaa";i:1;s:3:"sss";} )
My question is how do I get the string "aaa" and "sss" respectively.
Now try it with maybe_unserialized and unserialized, but without results on screen.
I don't know what maybe_unserialize is, but unserialize will work.
Try =
$datos = unserialize($datos[0]);
I have a "recruiter" table in my database which has different attributes and one of them is "Professions". "Professions" is a serialized array which I get from a multiple select form. And this works fine.
When I unserialize this attribute nothing is printed - no error, no text.
This is a code I was testing serialization with:
$sql = 'SELECT Company_name, Status, Size, Professions, Seniority_levels, Sector, Website, Location FROM Recruiter';
$query = mysql_query($sql, $con);
while($result = mysql_fetch_array($query, MYSQL_BOTH)){
$recruiters[] = array($result[0], $result[1], $result[2], $result[3], $result[4], $result[5], $result[6], $result[7]);
}
foreach($recruiters AS $recruiter){
$test = unserialize($recruiter[3]);
echo $test[0].'<br>';
}
So basically $test[0] prints nothing although the new lines are printed. Please help!
try printing the $test array and the $recruiters and the $recruiter arrays. See if the result is fine before the unserialisation of the data. If the query returns any data. Also try the while loop with mysql_fetch_assoc. Let me know of the results and if this solves the problem
test = unserialize($recruiter[3]); should become test = unserialize($recruiter[5]); since the sector field is the sixth column .
However what if somewhere in the future you might need to select rows where sectors equal smth ? serialize whont help you then so i suggest you have a look at a different implementation for the sector filed witch is called bitwize http://www.litfuel.net/tutorials/bitwise.htm
Edit
Asuming you hit the right column and the column contains a:1:{i:0;s:27: a:1:{i:0;s:27: a:38:{i:0;s:27: a:9:{i:0;s:39:, it looks like the serialized array is not fully saved in you're db, it's only part of it . So the unserialize function whont return you an array . Have a look at the length of the mysql field i assume you've set it smaller than you need so you're data is trimmed on insert/update .
Edit
a:1:{i:0;s:27: you're still missing the rest of the serialized array . s:27: means a string is following containint 27 characters, and you're serialized array stops there when it should look like
a:1:{i:0;s:27:"123456789012345678901234567";}
( a:1 stands for an array containing 1 value with it's content between {}, i:0; is the array key 0, s:27:""; stands for a string containing 27 characters as the value for the i:0 key ) .