I am having array problems and need help simplifying the answer. Now without me pasting and typing out from a greasemonkey script(Javascript), I am just pasting a little code from it:
//THIS LINK IN BROWSER IS WHAT IM GETTING FROM THE JS SIDE OF THE CODE. NOW I CAN GET THE DATA= , ID=, AND &SA=,&DA=, &SPY=, AND &SENTRY=.
//THE &WEAPONS=0,4674,72|1,19,71|1,370,51|2,300,75|2,239,73|3,482,74|3,354,68
/php/Armory.php?data=ID=4518188&GOLD=6559178&SA=1805135169&DA=22677617&SPY=2841765807&SENTRY=2703794914&WEAPONS=0,4674,72|1,19,71|1,370,51|2,300,75|2,239,73|3,482,74|3,354,68
I am having problems in my PHP to separate the array after &WEAPONS=. I've tried several things like split or even array_chunk, and all I get is the same answer which is what shows after weapons= part when I echo or print_r.
I want to separate this into 3 sections in PHP then have SQL insert the answer into the database if at all possible...
Below is some of the code I've done in PHP.
<?php
$list = $_REQUEST['WEAPONS'];
$list = explode("^", $list);
print_r(array_chunk($list, 3));
?>
OUTPUT:
Array ( [0] => Array ( [0] => 0,4674,72|1,19,71|1,370,51|2,300,75|2,239,73|3,482,74|3,354,68 ) )
I want this part divided up into 3 parts for a table on DB which is stat, wcount, and weaponNr.
0,4674,72|1,19,71|1,370,51|2,300,75|2,239,73|3,482,74|3,354,68
When divided up it will look like this:
stat = 0
count = 4674
weaponNr = 72
--------
stat = 1
count = 19
weaponNr = 71
--------
stat = 1
count = 370
weaponNr = 51
etc.....
--------
Sorry for the long explanation but if anyone can help, I'd appreciate this cause I am not a pro at coding or asking how lol...
To separate the string into an array this works:
function weaponsToArray($string) {
$weapons = [];
foreach (explode('|', $string) as $dataRow) {
$data = explode(',', $dataRow);
$weapons[] = [
'stat' => $data[0],
'count' => $data[1],
'weaponNr' => $data[2],
];
}
return $weapons;
}
$weapons = weaponsToArray($_GET['WEAPONS']);
Related
I'd like to be able to calculate the length of the shortest sub-string required to achieve complete uniqueness.
Lets say I have a varying length list of 32 character UUIDs, but what I'd like to achieve is shortenening them during reference to only be as long as is required to achieve uniqueness in their set. For instance, if I have the following set of UUID's (pipes inserted to illustrate the answer)...
428|07082e1f445e79501bebfa87396af
723|0785bffaf4747865c202dd0924c7f
b65|634be909d4e5590aa0cdc97251eef
3c4|d94c683624d75a273e3186ec65b78
09e|bd42af0404bcf90413e11c5b40fbb
011|004743d65466dae8a9a6bc814ef4b
1f1|889e04e3a453fbf57521de0a70b60
1ac|44707af8d4681875171ad47c61037
42f|7a6236deb4a9ead32ab2e816d73a3
83a|fe22086064eec87704127622b8165
I would only require the first three characters to achieve the same level of uniqueness as if I had used the full 32 character strings.
I'm curious if there is a formula for reaching that value. I know that I could put this in a couple nested loops, but I'd like to know if there is a more elegant or programmatic way of achieving this.
Edit: Just to be clear, the pipes are only to illustrate that I can achieve uniqueness after only 3 characters. The result of the formula/method should be an array of equal length with only the shortest strings derived from the given set, in this case, the first three chars only. Imagine that I want to use these in a URL, and that I can't have any ambiguity, but still want to be able to reference the same records as if I used the full string in each case.
EDIT2: Actually... as I think about it, no need for a result array, only an integer, the min length required in characters.
I managed to create some codes to achieve that. Take a look:
Code 1:
function check_un($array){
$arr = $array;
$len = 1;
$tmp = array();
while (list($key, $value) = each($arr)) {
$v = substr($value, 0, $len);
if (isset($tmp[$v])) {
$tmp = array();
$len++;
reset($arr); // start again
}
$tmp[$v] = true;
}
$tmp = array_keys($tmp);
array_shift($tmp);
return $tmp;
}
Basically, the previous code checks if given substring put as key is already set - meaning it's duplicated. That way, it goes to the beginning of the array and starts checking again with more letters.
Code 2: (smaller, but slower)
function check_un($array){
$array = array_values($array);
$len = 1;
$tmp = array();
for($i = 0; $i < strlen($array[0]); $i++){
if( count(array_unique( $tmp = array_map(function($v) use($len){ return substr($v, 0, $len); }, $array ) )) != count($array) ){
$len++;
}else{
break;
}
}
return $tmp; // this was set in the array_map part
}
Basically, the previous code checks if the quantity of unique elements of a given substring length is the same as the quantity of the original array. That way, if there are any duplicates, the quantity will be smaller, meaning that we need to use more positions.
There used to be a code 3 (the first I tried), but it's only available in the edit history.
You can test them with this:
$values = array(
'42807082e1f445e79501bebfa87396af',
'7230785bffaf4747865c202dd0924c7f',
'b65634be909d4e5590aa0cdc97251eef',
'3c4d94c683624d75a273e3186ec65b78',
'09ebd42af0404bcf90413e11c5b40fbb',
'011004743d65466dae8a9a6bc814ef4b',
'1f1889e04e3a453fbf57521de0a70b60',
'1ac44707af8d4681875171ad47c61037',
'42f7a6236deb4a9ead32ab2e816d73a3',
'83afe22086064eec87704127622b8165'
//,'42807082e1f445e795aaaaaaaaaaaaa' // add this to test with more letters
);
$val = check_un($values);
The result (for both cases):
Array
(
[0] => 428
[1] => 723
[2] => b65
[3] => 3c4
[4] => 09e
[5] => 011
[6] => 1f1
[7] => 1ac
[8] => 42f
[9] => 83a
)
See them in action here:
Code 1;
Code 2.
You can change the returned value to get only the $len variable.
You could utilize Array.prototype.reduce(), Object.hasOwnProperty() recursion; create an object to store values of unique character set, set object name to first two characters if name is not a property of object, else set first n characters until each property in object is unique
var arr = ["42807082e1f445e79501bebfa87396af "
, "7230785bffaf4747865c202dd0924c7f"
, "b65634be909d4e5590aa0cdc97251eef"
, "3c4d94c683624d75a273e3186ec65b78"
, "09ebd42af0404bcf90413e11c5b40fbb"
, "011004743d65466dae8a9a6bc814ef4b"
, "1f1889e04e3a453fbf57521de0a70b60"
, "1ac44707af8d4681875171ad47c61037"
, "42f7a6236deb4a9ead32ab2e816d73a3"
, "83afe22086064eec87704127622b8165"];
var obj = {};
arr.reduce((o, uuid) => {
var n = 1;
(function re(key) {
var curr = uuid.slice(0, key);
if (!o.hasOwnProperty(curr)) {
o[curr] = uuid;
} else {
re(key + 1)
}
}(n))
return obj
}, obj);
console.log(obj, "arr length:", arr.length
, "obj keys length:", Object.keys(obj).length);
I'm trying to set up a comments system on photos.
I understand how to use $.getJSON when the array is like this:
get.php:
$var = 5;
echo json_encode(array('var'=>$var));
main.php:
$.getJSON("get.php",function(data){
number = data.var; // number = 5
});
But I have a more complex thing.
My comments table has these 4 columns: id | photo_id | comment | date
For example let's say we're trying to retrieve the comment data from the photo with
photo_id == 1.
We don't know how many comments there might be.
In getcomments.php:
$photoid = 1;
$comment = mysqli_query($conn,"SELECT * FROM comments WHERE photo_id='$photoid'");
while($commentrow = $comment->fetch_assoc()) {
$comments[] = $commentrow;
}
Then you encode it:
echo json_encode($comments);
Which prints something like this (the photo has 2 comments):
[{"id":"1","photo_id":"1","comment":"text","date":"23858556"},{"id":"2","photo_id":"1","comment":"text","date":"23858561"}]
How do I declare variables for the comments array?
$.getJSON("getcomments.php",function(data){
// how do I declare variables for the comments array, especially since you don't know how many there might be?
});
Additionally, I have two json arrays that need to be echoed within the same PHP file. i.e. echo json_encode(array('img1'=>$img1link)) and echo json_encode($comments); need to be echoed within the same PHP file, but it made the code stop working altogether.
If you want to display the comments you need to loop over the array. You can use for loop or forEach function.
$.getJSON("getcomments.php",function(data){
data.forEach(function(comment) {
$('div').append('<span>' + comment.comment + '</span>');
});
});
To display two JSONs you need to combine them into one JSON object.
echo json_encode(array('img' => $img1link, 'comments' => $comments));
[{"id":"1","photo_id":"1","comment":"text","date":"23858556"},{"id":"2","photo_id":"1","comment":"text","date":"23858561"}]
Using this JSON, data is an array and you should manage it as an array. You can loop through it using simple loops (for, while...) or using new functional methods like forEach, map, filter....
Please try with this example:
$.getJSON("getcomments.php",function(data){
data.forEach(function(item, index, all) {
console.log(item.comment);
});
});
Declare an object, and push it to the array.
var commentsArr = [];
for (var i = 0; i < data.length; i++) {
var objToPush = {
id: data.id,
comment: data.comment,
date: data.date
}
commentsArr.push(objToPush);
}
i have some problems with CSV files.
I have about 50 csv files, all looks the same like this below.
I need to import them into Php array - (later i put them into js var, and use in diagrams)
But the CSV dont looks like should do (i cant change it) - It have some data at top (first 10 lines) - i need to use them in different places (just show them - like "Kategoria:";"ROLNICTWO, LEŚNICTWO I ŁOWIECTWO"; - is a title)
"Okres sprawozdawczy:";"Dane roczne";
"Kategoria:";"ROLNICTWO, LEŚNICTWO I ŁOWIECTWO";
"Grupa:";"SKUP PRODUKTÓW ROLNYCH";
"Podgrupa:";"Skup produktów na 1 ha użytków rolnych";
"Wymiary:";"Wykaz produktów, Lata";
"Kod";"Jednostka terytorialna";"buraki cukrowe";"buraki cukrowe";"buraki cukrowe";"buraki cukrowe";
"2010";"2011";"2012";"2013";
"[kg]";"[kg]";"[kg]";"[kg]";
"1100000000";" ŁÓDZKIE";"278";"355";"363";"333";
"1140000000";" MAZOWIECKIE";"247";"250";"286";"348";
"2120000000";" MAŁOPOLSKIE";"67";"87";"114";"127";
"2240000000";" ŚLĄSKIE";"168";"218";"245";"281";
"3060000000";" LUBELSKIE";"1139";"1170";"1235";"1346";
"3180000000";" PODKARPACKIE";"249";"208";"342";"404";
"3200000000";" PODLASKIE";"6";"30";"5";"0";
"3260000000";" ŚWIĘTOKRZYSKIE";"479";"482";"337";"534";
"4080000000";" LUBUSKIE";"184";"141";"264";"229";
"4300000000";" WIELKOPOLSKIE";"1102";"1412";"1485";"1532";
"4320000000";" ZACHODNIOPOMORSKIE";"522";"830";"909";"642";
"5020000000";" DOLNOŚLĄSKIE";"1044";"1045";"1274";"1136";
"5160000000";" OPOLSKIE";"1392";"1386";"2113";"1660";
"6040000000";" KUJAWSKO-POMORSKIE";"1588";"2040";"2272";"2252";
"6220000000";" POMORSKIE";"624";"748";"724";"879";
"6280000000";" WARMIŃSKO-MAZURSKIE";"153";"150";"163";"167";
How i can print them as array - to looks like this:
[0] => Array
(
[0] Okres sprawozdawczy
[1] Dane roczne
)
[1] => Array
(
[0] Kategoria
[1] ROLNICTWO, LEŚNICTWO I ŁOWIECTWO
)
[2] => Array
(
[0] Grupa:
[1] SKUP PRODUKTÓW ROLNYCH
)
etc. first 5 lines of CSV lines.
But later from line 7 (6 is empty) - line 7,8,9 is one header..
"Kod" - its "1100000000"
"Jednostka terytorialna" - its "ŁÓDZKIE"
"buraki cukrowe","2010","[kg]" - "278"
"buraki cukrowe","2011","[kg]" - "355"
"buraki cukrowe","2012","[kg]" - "363"
"buraki cukrowe","2013","[kg]" - "333"
3 headers for one data, so i need i think something like that:
[6] => Array ([0] buraki cukrowe => Array ([0] 2010 => Array ([0] kg => Array ([0] 278)
Where the "278" is data what i need to use and put in to JS VAR.
Im not sure its good way to do this, please help me out..
First you set this file on variable, you can use file_get_content() like this
$csvData = file_get_contents('your_file.csv');
you can do it for all the files you need to add
After you have your $csvData you just have to explode and chunk it like this
$explodedCsvData = explode(';',$csvData);
$chuckedCsvData = array_chunk($explodedCsvData,2);
Something like that could do the trick :
$file = fopen('your-file.csv');
$header = true;
$headers = [];
$data = [];
while($line = fread($file)) {
if($line === '') { // Transition from headers to columns info
$header = false;
$line = fread($file);
$label = explode(';', $line);
$l = count($label);
$year = array_pad(explode(';', fread($file)), -$l, null);
$unit = array_pad(explode(';', fread($file)), -$l, null);
$column = [];
for($i=0; $i<$l; ++$i) {
$column[] = [
'label' => $label[$i],
'year' => $year[$i],
'unit' => $unit[$i]
];
}
}
elseif($header) { // Still in the first lines
$headers[] = explode(';', $line);
}
else { // After the columns parsing
$data[] = explode(';', $line);
}
}
fclose($file);
I have an array.
Array
(
[0] => Array
(
[title] => Badminton Men's Singles Gold Medal Kashyap Parupalli
[mp4] => http://www.tensports.com/media/video/kashyap.mp4
[webm] => http://www.tensports.com/media/video/kashyap_VP8.webm
[playThumb] => {filedir_2}Kashyap_medal.jpg
[videoPoster] =>{filedir_3}Kashyap_medal.jpg
)
[1] => Array
(
[title] => Boxing Men's Welter (69kg) Silver medal: Mandeep Jangra
[mp4] => http://www.tensports.com/media/video/MandeepJangraMedal.mp4
[webm] => http://www.tensports.com/media/video/MandeepJangraMedal_VP8.webm
[playThumb] => {filedir_2}Mandeep_Jangra_medal.jpg
[videoPoster] =>{filedir_3}Mandeep_Jangra_medal.jpg
)
)
I am trying to convert it in a object like below.
Javascript Format required :
videos = [
{
src : [
'http://www.tensports.com/media/video/kashyap_VP8.webm',
'http://www.tensports.com/media/video/kashyap.mp4'
],
poster : '{filedir_2}Kashyap_medal.jpg',
title : "Badminton Men's Singles Gold Medal Kashyap Parupalli"
},
{
src : [
'http://www.tensports.com/media/video/MandeepJangraMedal.mp4',
'http://www.tensports.com/media/video/MandeepJangraMedal_VP8.webm'
],
poster : '{filedir_2}Mandeep_Jangra_medal.jpg',
title : "Boxing Men's Welter (69kg) Silver medal: Mandeep Jangra"
}
];
what I have done :
var videoObject = $.parseJSON(<?php echo $js_VideoURL ?>);//where $js_VideoURL = json_encode($above-array);
$.each(videoObject, function(key, value) {
console.log('stuff : ' + key + ", " + value);
});
It's giving me error.I am uncertaing about getting the data in required format.Any help?
The format you're expecting in javascript is not compatible with the php array you've given.
Going from there I am assuming that is the problem, since you didn't give the exact error message you're encountering. From what I can gather you're missing a piece of PHP to put the video's in the correct format. To solve that you can do the following:
Note the comments in the code, they should explain what is going on.
PHP:
// $videos is assumed to be the array you've given in your question
$arr = [];
foreach ($videos as $video) {
// Create video object
$obj = new stdClass;
$obj->src = [
$video['webm'],
$video['mp4']
];
$obj->poster = $video['playThumb'];
$obj->title = $video['title'];
$arr[] = $obj;
}
// $arr is now the output you would need for processing
Javascript:
var videoObject = <?php echo $js_VideoURL ?>; //where $js_VideoURL = json_encode($arr);
$.each(videoObject, function(key, value) {
console.log('stuff : ' + key + ", " + value);
});
Edit:
Your first mistake is as Quentin mentioned that you're putting the json directly into javascript, which means it will be interpreted as a native javascript object. I missed that in my original answer.
It means you indeed do not need to use $.parseJSON to get the object you want. I changed my answer to reflect that.
Note:
Your code implies that you have Javascript snippets in your php / html templates. This is considered bad practice, and can be resolved with relative ease.
What you could do is put the json in a data attribute of the relevant html element on the page (escape the json before printing) then picking up the json string using jQuery on initialization with
var object = $element.data('json');
Using this (jQuery will automatically try parse the string as json) it will be ready for use.
The JSON format is a subset of JavaScript literal syntax
json_encode outputs JSON (which, if just dumped in JS, will be treated as a literal)
parseJSON takes a string of JSON and converts it to a data structure
Therefore: Don't use parseJSON as it will force the object you have into a string ("[Object object]") and then try to parse that as JSON.
Just:
var videoObject = <?php echo $js_VideoURL ?>;
Come on.. did you even check PHP docs, or even google json encode!?!?!
var videoObject = <?php echo json_encode($js_VideoURL); ?>;
I would like to access to the data inside an array of array that I'm sending with ajax to a .php page.
Creating the array of arrays in the function before sending
var xi = new Array(maxests);
$(".mtable").find(".allownumericwithdecimal").each(function(){
var nth = ((i) % maxests) + 3
var alt = $(this).parent().parent().find("td:first").html()
var est = $('.mtable').find("thead tr:first td:nth-child("+nth+")").html()
var pay = $(this).val()
xi[i] = new Array(alt,est,pay);
i++;
})
Output on php:
Array(
[data] => Array
(
[name] =>
[description] =>
[project] => 1
[ae] => [["Alternativa 1","Estado N. 1","1"],["Alternativa 1","Estado N. 2","23"],["Alternativa 2","Estado N. 1","33"],["Alternativa 2","Estado N. 2","43"]]
))
I would like to access the data inside ae.
echo $_POST['data']['ae'][0][0];
I'm trying this one, but not luck. How can I get the value of each one?
If that's a var_dump($_POST) or print_r($_POST), then this
[ae] => [["Alternativa 1","Estado N. 1","1"],["Alternativa 1","Estado N. 2","23"],["Alternativa 2","Estado N. 1","33"],["Alternativa 2","Estado N. 2","43"]]
is a string
$ae=json_decode($_POST['data']['ae']);
echo $ae[0][0]; // what you thought $_POST['data']['ae'][0][0]; would do
foreach ($ae as $a){
print_r($a);
}
http://uk1.php.net/json_decode
Your array appears to be in an array
$ae = $_POST[0]['data']['ae'];
print_r($ae);
Should give you the breakdown of $ae. So in your example the first element of the first array would be
echo $_POST[0]['data']['ae'][0][0];
output:
Alternativa 1
I hope this helps.