PHP array and json_encode (separated with comma) - javascript

I am literally cracking my head to covert the PHP array to JavaScript array and convert the same in the correct format. This is what I have
My PHP array is stored in $data (this comes from a SQLserver query) which I am converting to a JavaScript array using json_encode.
Here is the code $javaarray = json_encode($data); When I echo the result this is what I am getting
{"VERTICAL":"PROVISIONING","dcount":381890}
{"VERTICAL":"BILL DELIVERY","dcount":171169}
{"VERTICAL":"BILLING","dcount":45197}
{"VERTICAL":"RISK AND CREDIT","dcount":51533}
{"VERTICAL":"CUSTOMER ACCOUNTING","dcount":136097}
{"VERTICAL":"AIRTEL MONEY","dcount":7826}
{"VERTICAL":"ANALYTICS","dcount":2946}
{"VERTICAL":"CONTROLS","dcount":5615}
Now I want to get the dcount part only to feed it back to my jQuery function in the following format
[381890,171169,45197,51533,136097,7826,2946,5615]
I tried working around with implode(), join() but somehow not getting even closer to the above format.
I am posting the
$array = array($data);
print_r($array);
result also
Array ( [0] => Array ( [VERTICAL] => PROVISIONING [dcount] => 381890 ) ) Array ( [0] => Array ( [VERTICAL] => BILL DELIVERY [dcount] => 171169 ) ) Array ( [0] => Array ( [VERTICAL] => BILLING [dcount] => 45197 ) ) Array ( [0] => Array ( [VERTICAL] => RISK AND CREDIT [dcount] => 51533 ) ) Array ( [0] => Array ( [VERTICAL] => CUSTOMER ACCOUNTING [dcount] => 136097 ) ) Array ( [0] => Array ( [VERTICAL] => AIRTEL MONEY [dcount] => 7826 ) ) Array ( [0] => Array ( [VERTICAL] => ANALYTICS [dcount] => 2946 ) ) Array ( [0] => Array ( [VERTICAL] => CONTROLS [dcount] => 5615 ) )

Try something like this
$dcounts = array();
foreach ($data as $row) {
$dcounts[] = $row['dcount'];
}
$javaarray = json_encode($dcounts);

$dcounts = json_encode(array_map(function($v) { return $v['dcount'] }, $javaarray));

$data = '{"VERTICAL":"PROVISIONING","dcount":381890}
{"VERTICAL":"BILL DELIVERY","dcount":171169}
{"VERTICAL":"BILLING","dcount":45197}
{"VERTICAL":"RISK AND CREDIT","dcount":51533}
{"VERTICAL":"CUSTOMER ACCOUNTING","dcount":136097}
{"VERTICAL":"AIRTEL MONEY","dcount":7826}
{"VERTICAL":"ANALYTICS","dcount":2946}
{"VERTICAL":"CONTROLS","dcount":5615}';
//split data into array
$keywords = preg_split("/[\n]+/", $data);
//convert into proper json format
$jsonobject = implode(',',$keywords);
$jsonobject = '['.$jsonobject.']';
//convert json into array
$array = json_decode($jsonobject);
//for each and save dcount value
$dcount = array();
foreach($array as $row){
$dcount[] = $row->dcount;
}
//again convert dcount values into json
$dcountjson = json_encode($dcount);
print_r($dcountjson);

Related

Autocomplete from array and get the corresponding id

Just wondering if someone knows a way to be able to autocomplete an input field after you type 3 letters then also get the id of the corresponding value?
I tried something like this with the UI Jquery:
It works great with the test array, but not with the real array im trying to use. Is it because the format is wrong? I include the array before json_encode and after.
var test = ["1899 Hoffenheim vs Borussia Dortmund", "SD Eibar vs Granada CF", "Fiorentina vs AS Roma"];
var availableTags = <?php echo json_encode($testArray); ?>;
console.log(availableTags);
$( "#test" ).autocomplete({
source: test
});
});
Before json_encode
Array
(
[0] => Array
(
[id] => 33820950
[match] => 1899 Hoffenheim vs Borussia Dortmund
)
[1] => Array
(
[id] => 33820951
[match] => SD Eibar vs Granada CF
)
[2] => Array
(
[id] => 33820952
[match] => Fiorentina vs AS Roma
)
[3] => Array
(
[id] => 33820991
[match] => Hibernian vs Rangers
)
[4] => Array
(
[id] => 33821044
[match] => RKC Waalwijk vs FC Twente
)
[5] => Array
(
[id] => 33821045
[match] => Middlesbrough vs Stoke City
)
[6] => Array
(
[id] => 33821108
[match] => Deportivo La Coruña vs CD Tenerife
)
[7] => Array
(
[id] => 33821138
[match] => Zaglebie Lubin vs Legia Warszawa
)
[8] => Array
(
[id] => 34096342
[match] => Everton vs Arsenal
)
[9] => Array
(
[id] => 34096343
[match] => Aston Villa vs Southampton
)
)
After json_encode
[{"id":"33820950","match":"1899 Hoffenheim vs Borussia Dortmund"},{"id":"33820951","match":"SD Eibar vs Granada CF"},{"id":"33820952","match":"Fiorentina vs AS Roma"},{"id":"33820991","match":"Hibernian vs Rangers"},{"id":"33821044","match":"RKC Waalwijk vs FC Twente"},{"id":"33821045","match":"Middlesbrough vs Stoke City"},{"id":"33821108","match":"Deportivo La Coru\u00f1a vs CD Tenerife"},{"id":"33821138","match":"Zaglebie Lubin vs Legia Warszawa"},{"id":"34096342","match":"Everton vs Arsenal"},{"id":"34096343","match":"Aston Villa vs Southampton"}];
Update:
Sorry, I misunderstood you at first. I guess you want to save all text values of the key match to a json array. So I take your $testArray, loop through it and assign everything to a new array that it matches the format.
Try this:
<?php
$array = [];
$i = 0;
$id = 0;
$ids = '[';
$availableTags = '[';
foreach($testArray as $val) {
$id[] = "\"".$val[$i]['id']."\"";
$array[] = "\"".$val[$i]['match']."\"";
$i++;
}
$id = implode(', ', $id);
$array = implode(', ', $array);
$availableTags .= $array . '];';
$ids = $id . '];';
?>
var availableIds = <?= $ids; ?>
var availableTags = <?= $availableTags; ?>
console.log(availableTags);
$( "#test" ).autocomplete({
source:
return {
label: availableTags,
value: availableIds
};
});
});
Finished working code. Where you can search for the match and both match and the corresponding id gets saved.
<form action="" method="POST" >
<input id="match_search" name="match_search" onChange="this.form.submit()">
<input id="match_id" name="match_id" hidden>
</form>
<?php
if (isset($_POST['match_search'])) {
$match = $_POST['match_search'];
$match_id = $_POST['match_id'];
echo $match.'<br>';
echo $match_id;
}
?>
<script>
var availableMatches = <?=json_encode($testArray); ?>;
$(function() {
$("#match_search").autocomplete({
delay: 0,
source: availableMatches,
select: function(event, ui) {
$('#match_search').val(ui.item.label);
$('#match_id').val(ui.item.value);
return false;
},
focus: function(event, ui) {
$("#match_search").val(ui.item.label);
return false;
}
});
});
</script>

How to get Session value which is an array in JavaScript?

I have a session set in a php page which stores an array as follows:
firstpage.php
$_SESSION["Counts"]=$some_array;
echo print_r($_SESSION["Counts"]);
Output:
Array ( [Finance] => Array ( [0] => 0 [1] => 3 [2] => 0 [3] => 0 [4] => 1 )
[Human resources] => Array ( [0] => 1 [1] => 5 [2] => 1 [3] => 0 [4] => 0 )
[Infrastructure] => Array ( [0] => 0 [1] => 3 [2] => 1 [3] => 0 [4] => 0 ) ) 1
Retrieving the session data in .js page
SecondJSpage.js
<script type="text/javascript">
var sessionValue= new Array();
var s= new Array();
var s1= new Array();
sessionValue = '<?php $_SESSION["Counts"]; ?>';
document.write(sessionValue); //Does not output anything
for( s1 in sessionValue) {
for( s in s1) {
document.write(s); //Does not output anything
document.write("<br />");
}}
</script>
Only arrays are not being retrieved. A simple session variable is getting displayed. How to solve this problem?
change this line up a little bit..
sessionValue = <?php echo json_encode($_SESSION["Counts"]); ?>;
Use json_encode() for this purpose (Javascript can handle JSON).
Check the manual: http://php.net/json_encode
You cannot echo an array.
<?php echo $_SESSION["Counts"]; // this is an array ?>
And you can't execute PHP within a .js file either (trying to parse PHP within SecondJSpage.js)

JSON Array parsing in PHP and updating in the database

Though this is a textbook problem, but I'm not able to parse from json object. I have a json object coming from a page, and I need to extract the ID,fieldText value so that I can update the table.
Here is how I'm capturing the json and converting it into array, not sure how to extract the values.
if(isset($_POST['postData'])){
$json = json_decode($_POST['postData'],true);
foreach ($json as $key => $value)
{
print_r($key);
//print_r($value);
foreach ($value as $k => $val)
{
//echo "$k | $val <br />";
} }
I need to update the table with [ID] and [fieldText] :
Result should like this::(1:Hello World), (2:The rising Star),(3: Terminator)
My JSON object is like this:
Array(
[fieldName] => Array
(
[0] => fieldText[1]
[1] => fieldText[2]
[2] => fieldText[3]
)
[fieldText] => Array
(
[0] => HelloWorld
[1] => The rising Star
[2] => Terminator
)
[ID] => Array
(
[0] => 1
[1] => 2
[2] => 3
))
Hi it seems that there are three arrays in your JSON, I think it would be better to change the way you generate the JSON to make it simple to understand.
// assumes $arr as the $_POST['postData'] in your case
$arr = array("1"=>"Hello World", "2"=>"The Rising Star", "3"=>"Terminator");
$j = json_encode($arr);
$json = json_decode($j,true);
foreach ($json as $key => $value)
{
echo '('.$key.','. $value.')';
}
The results are :
(1,Hello World)(2,The Rising Star)(3,Terminator)
Hope this can help you.
Hope you can do something like this.
$jsonData = Array(
'Name' => Array
(
0 => 'Text1',
1 => 'Text2',
2 => 'Text3'
),
'Value' => Array
(
0 => 'HelloWorld',
1 => 'The rising Star',
2 => 'Terminator'
),
'ID' => Array
(
0 => 1,
1 => 2,
2 => 3
)
);
$length = count($jsonData['ID']);
for($j=0;$j<$length;$j++) {
echo "(".$jsonData['ID'][$j].": ".$jsonData['Value'][$j].")<br/>";
}
In my opinion you should make your life easier by modifying the json array you receive with $_POST['data'];. If I were in your shoes my json would've been exactly as you need it:
{ 1:'Hello World', 2:'The rising Star',3:'Terminator' }
But if you are not able to change it for any reason I think you could use something like this (basing this example on your code):
$jsonData = json_encode($_POST['json'], true);
$id = $jsonData['ID'];
$fieldText = $jsonData['fieldText'];
$arr = array();
for ($i=0; $i < count($id); $i++) {
$arr[(int) $id[$i]] = $fieldText[$i];
}
var_dump($arr);
Hope this helps you!

Pass city name from php to js (part 2)

Cont. on Show Malaysia cities based on states chosen
City data json ($cityJsonObject)
Array ( [0] => stdClass Object ( [cityId] => c1 [cityName] => Kajang [cityStateId]
=> s2 ) [1] => stdClass Object ( [cityId] => c2 [cityName] => Seputeh
[cityStateId] => s1 ) [2] => stdClass Object ( [cityId] => c3 [cityName] => Shah
Alam [cityStateId] => s2 ) [3] => stdClass Object ( [cityId] => c4 [cityName] =>
Klang [cityStateId] => s2 ) [4] => stdClass Object ( [cityId] => c5 [cityName] =>
Kepong [cityStateId] => s1 ))
code (cityName)
<?php
for($i = 0; $i < count($cityJsonObject); $i++)
{
echo $cityJsonObject[$i]->cityName;
//PASS VARIABLE TO JS
}
?>
<script type="text/javascript">
//GET VARIABLE FROM PHP AND DISPLAY CITY NAME
</script>
From above code, I can get the following:
Kajang
Seputeh
Shah Alam
Klang
Kepong
My question is how to pass the above city name into a variable and pass to js? How should I do?
You can use json_encode and output a string which will be parsed easily by javascript
Try this code
<?php
$array_to_js = array();
for($i = 0; $i < count($cityJsonObject); $i++)
{
$array_to_js[] = $cityJsonObject[$i]->cityName;
}
?>
<script type="text/javascript">
//GET VARIABLE FROM PHP AND DISPLAY CITY NAME
var js_array = <?php echo json_encode($array_to_js, JSON_HEX_QUOT) ?>;
</script>
<?php
echo '<script type="text/javascript">';
// your php code here maybe you can need json_encode(), I'm not sure I get what you mean.
echo json_encode($cityJsonObject);
echo '<script>';
?>

How to properly format JSON

I asked a question earlier, which all revolved around a JSON formatting problem. I have a PHP page, which just grabs rows from a MYSQL database, and returns them. However, i'm unsure how to format them so all the columns I get are a set, and for each row, it creates a new set. I'm not sure what is common practice to do to encode things like this.
e.g. this is what I want (if it is even correct):
{ "message": [
{
"chat":"Hello, world!",
"time":"2014-05-09 17:32:00",
"username":"Josue"
},
{
"chat":"This is my second message.",
"time":"2014-05-09 17:32:05",
"username":"Josue"
}
]
}
That way, I can parse using $.parseAJAX, and get access to my data like: data.message[0].chat, and it would return "Hello world!".
Here is what I am currently doing:
$SQL = sprintf('SELECT time_sent, chat, username FROM Messages where time_sent >= date(\'%s\')', $last_chat_time);
$result = mysql_query($SQL);
$messages = Array();
while ( $row = mysql_fetch_assoc($result) ) {
$messages[] = 'chat';
$messages[] = $row['chat'];
$messages[] = 'time';
$messages[] = $row['time_sent'];
$messages[] = 'username';
$messages[] = $row['username'];
}
$loopCount = count($chats);
if(count($messages) > 0){
/*
$sexyJSON = '{message: [';
for($i = 0; $i < $loopCount; $i++){
$sexyJSON .= '{"chat":"'.$chats[$i].'","time":"'.$times[$i].'","username":"'.$usernames[$i].'"},';
}
$sexyJSON = substr($sexyJSON,0,strlen($sexyJSON)-1);
$sexyJSON .= ']}';
$newMessages = $sexyJSON;
echo $sexyJSON;
*/
echo json_encode($messages);
}
When I simply encode my array, it returns something like this:
["chat","Hello, world!","time","2014-05-09 17:32:00","username","Josue","chat","hmmm","time","2014-05-09 17:48:34","username","asdf"]
What would I have to do to group chat with the message, date with the date, and username with the username in a key-value pair?
The format of the mysql_fetch_assoc should be
array('chat'=>'Some chat', 'time_sent'=>'123456', 'username'=>'abcdefg')
json_encode would directly translate this to
{"chat":"Some chat", "time_sent":"123456", "username":"abcdefg"}
So in your loop, if you simply do $mesages[] = $row; and leave your json_encode call as-is, it should work as shown above. However, you can alter your SQL statement to give the columns an alias so that time_sent simply shows as the property time
This is what i would do:
$SQL = sprintf('SELECT time_sent, chat, username FROM Messages where time_sent >= date(\'%s\')', $last_chat_time);
$result = mysql_query($SQL);
$messages = array();
while ( $row = mysql_fetch_assoc($result) ) {
$arr = array();
$arr['chat'] = $row['chat'];
$arr['time'] = $row['time_sent'];
$arr['username'] = $row['username'];
$messages[] = $arr;
}
$loopCount = count($chats);
if(count($messages) > 0){
echo json_encode($messages);
}
This will output if not encoded:
Array
(
[0] => Array
(
[chat] => chat_0
[time] => time_sent_0
[username] => username_0
)
[1] => Array
(
[chat] => chat_1
[time] => time_sent_1
[username] => username_1
)
[2] => Array
(
[chat] => chat_2
[time] => time_sent_2
[username] => username_2
)
[3] => Array
(
[chat] => chat_3
[time] => time_sent_3
[username] => username_3
)
)
And this if encoded:
[{"chat":"chat_0","time":"time_sent_0","username":"username_0"},
{"chat":"chat_1","time":"time_sent_1","username":"username_1"},
{"chat":"chat_2","time":"time_sent_2","username":"username_2"},
{"chat":"chat_3","time":"time_sent_3","username":"username_3"}]
To parse the JSON
lets say you have your JSON results in a data var
var obj = $.parseJSON(data);
$.each(obj, function(i, value){
console.log(value.chat);
});
You need to work with multi-dimensional arrays in order to get this to work. The code below has been edited to assign values to named indexes and append these to the 2nd level to the $messages array.
$messages = Array();
while ( $row = mysql_fetch_assoc($result) ) {
$messages[] = Array(
'chat' => $row['chat'],
'time' => $row['time_sent'],
'username' => $row['username']
);
}
The while cycle should be like this:
while ( $row = mysql_fetch_assoc($result) ) {
$arr = array();
$arr['chat'] = $row['chat'];
$arr['time'] = $row['time_sent'];
$arr['username'] = $row['username'];
$messages[] = $arr;
}
Save a little time by getting the field names correct within the SQL.
$SQL = sprintf('SELECT time_sent as `time`, chat, username FROM Messages where time_sent >= date(\'%s\')', $last_chat_time);
$result = mysql_query($SQL);
$messages = array();
while ($row = mysql_fetch_assoc($result)) {
$messages[] = $row;
}
echo json_encode($messages);
IMO returning an empty array when there are no messages is better than returning nothing, as now you have a way to differentiate if your php worked vs if you had no messages, from within your JavaScript code.

Categories

Resources