Is this a JSON array: http://flamencopeko.net/icons_ajax.php?
Source: http://flamencopeko.net/icons_ajax.txt
$urls = array(); foreach (glob(dirname(__FILE__) . '/ico/*.gif') as $file) { $urls[] = 'http://flamencopeko.net/ico/' . basename($file); };
$index = 0;
if (isset($_GET['index'])) {
$index = (int) $_GET['index'];
if ($index > (count($urls) - 1)) {
// Out of bounds, reset
$index = 0;
}
}
$previous = $index - 1;
$next = $index + 1;
if ($previous < 0) {
$previous = count($urls) - 1;
}
if ($next == count($urls)) {
$next = 0;
}
echo json_encode(array(
'total' => count($urls),
'url' => $urls[$index],
'next' => $next,
'prev' => $previous,
'alls' => $urls
));
I'm trying to use it with php. Works with JavaScript. I've tried json_decode() and more, but no output yet.
What you've shown is a JSON object. It contains an array inside, but the entire thing is an object. Think of it this way-JSON could be a key-value data, making it an object, or it could be an array-single values, no keys such as
[1,2,3,"some string",34,"another string"]
What you've shown is a completely valid JSON object. Whether it will suit your needs-we cannot say. You could take a look at json.org for the exact specifications and what is considered a valid JSON.
Also any array passed on to json_encode() will output a valid JSON.
I like to use the online json viewer at http://jsonviewer.stack.hu/ - which shows you have a valid json object; which you could use to see that it consists of some header info and an array of 406 images in the 'alls' array.
Related
How can I convert an array of arrays to a single array in Vue.js? In my php back-end, I have the code below that fetch data from database. My problem now is I don't know how to convert them in my js side to a single array.
PHP side:
$name = DB::raw("CONCAT(emp.first_name, ' ', emp.last_name) AS name");
$nameCol = [];
$usedDate = '2018-07';
$date = 'attendance.date';
$total = 'attendance.total';
for($i = 1; $i<32; $i++){
if($i<10) $i = '0'.$i;
$names = DB::table('attendance')
->leftJoin('m_emp','m_emp.emp_key','=','attendance.emp_key')
->select($name,$date,$total)
->where(DB::raw("(DATE_FORMAT(attendance.date,'%Y-%m-%d'))"), '=', $usedDate.'-'.$i)
->get();
array_push($nameCol,$names);
}
return (array)$nameCol;
Result is like this:
Inside of each array is like this:
And finally inside it is this:
Can I do for loop on it to transform it to a single array and how? Or can I right away search for an item inside it? Because I have tried search using a way like this but I think this only search or works in a single array (that's my reason why I want to merge them to one array):
Vue.js side
list.find( empName=> empName.name === 'John Doe')
//let's assume list is the variable that receives data returned from php
//result for this one is undefined.
Any idea how ?
You can use array_merge instead of array_push.
I guess you are using Laravel , you have to convert the collection to array before merging that, see the example :
$name = DB::raw("CONCAT(emp.first_name, ' ', emp.last_name) AS name");
$nameCol = [];
$usedDate = '2018-07';
$date = 'attendance.date';
$total = 'attendance.total';
for($i = 1; $i<32; $i++){
if($i<10) $i = '0'.$i;
$names = DB::table('attendance')
->leftJoin('m_emp','m_emp.emp_key','=','attendance.emp_key')
->select($name,$date,$total)
->where(DB::raw("(DATE_FORMAT(attendance.date,'%Y-%m-%d'))"), '=', $usedDate.'-'.$i)
->get();
// use array_merge
$nameCol = array_merge($nameCol,$names->toArray());
}
return (array)$nameCol;
So Here is my php file code
GetUserArray.php
$Users = array('7'=>'samei', '4'=>"chaya", '10'=>'abetterchutia');
echo json_encode($Users);
and this is my ajax request
$.ajax({
url: './GetUserArray.php',
type: 'POST',
dataType: "json",
success: function(users) {
console.log(users);
$.each( users, function( key, value ) {
console.log(key, value);
});
}
});
now what it gives me is in the console is an object sorted by the keys of that array while i want the orignal order which was 7 4 10 in my php file
Object {4: "chaya", 7: "samei", 10: "abetterchutia"}
4 chutiya
7 sali
10 abetterchutia
The problem with using hashmaps is that they don't actually specify order. Though, in PHP, an array is actually an ordered hashmap, so it does. Once you translate that into an object in Javascript, the order is no longer preserved. The only way to guarantee order in Javascript is to use an array.
So in PHP this works as expected and preserves order.
$arr = [4 => "I'm first", 1 => "I'm second", 3 => "I'm third"];
foreach($arr as $value) {
echo $value, "\n";
}
Which gives us
I'm first
I'm second
I'm third
But encode that to Javascript Object Notation (i.e. JSON) and you get an object, because in Javascript arrays don't have keys, they have indexes.
echo json_encode($arr);
Gives us...
{"4":"I'm first","1":"I'm second","3":"I'm third"}
If you tried to do the same in Javascript with this object you might not get the same order
var obj = {"4":"I'm first","1":"I'm second","3":"I'm third"};
var s = "";
for(var x in obj) {
s += + obj[x] + "\n";
}
document.write("<pre>" + s + "</pre>");
This might give you something more like...
I'm second
I'm third
I'm first
So the only way to fix that is to use an array...
json_encode(array_values($arr));
Now this gives us...
["I'm first","I'm second","I'm third"]
And the order is maintained.
However, if you want to preserve the keys as well, you'll have to create an array of objects.
$json = [];
foreach($arr as $key => $value) {
$json[] = [$key => $value];
}
echo json_encode($json);
Now you get...
[{"4":"I'm first"},{"1":"I'm second"},{"3":"I'm third"}]
Which in javascript, works perfectly as expected...
for(var x in obj) {
for(var n in obj[x]) {
obj[x][n]; // now you can both maintain order and have access to the key
}
}
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 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); ?>;