Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
This is javascript serialized array:
[{"id":1},{"id":2},{"id":3,"children":[{"id":4,"children":[{"id":5},{"id":6},{"id":7}]},{"id":8}]}]
How to save this (dynamic) to mysql with php like this:
***********************************
| id | subsite_id | orderby |
1 0 0
2 0 1
3 0 2
4 3 0
5 4 0
6 4 1
7 4 2
8 3 1
***********************************
Thanks for answer.
This might not be the best solution, but it's certainly a solution. Recently, I learned about RecursiveIterators and their cousin, RecursiveIteratorIterator. So, I took it upon myself to use them in everything I code (relevant XKCD: https://xkcd.com/208/).
I hacked this up quickly:
class ChildIDIterator implements RecursiveIterator{
private $_array;
private $_position = 0;
private $_parent;
public function __construct(array $array, $parent=0) {
$this->_array = $array;
$this->_parent = $parent;
}
function valid(){
return isset($this->_array[$this->_position]);
}
function current() {
return $this->_array[$this->_position]['id'];
}
function next() {
$this->_position++;
}
function rewind() {
$this->_position = 0;
}
function key() {
return $this->_position;
}
function hasChildren(){
return isset($this->_array[$this->_position]['children']);
}
function getChildren(){
return new self(
$this->_array[$this->_position]['children'],
$this->_array[$this->_position]['id']
);
}
function getParent(){
return $this->_parent;
}
}
This recursively iterates over your (decoded) array and returns the id values. To use it, you can do this:
$json = '[{"id":1},{"id":2},{"id":3,"children":[{"id":4,"children":[{"id":5},{"id":6},{"id":7}]},{"id":8}]}]';
$array = json_decode($json, TRUE);
$iterate = new RecursiveIteratorIterator(new ChildIDIterator($array), RecursiveIteratorIterator::SELF_FIRST);
foreach($iterate as $order=>$id){
echo "UPDATE sites SET subsite_id={$iterate->getParent()}, orderby={$order} WHERE id={$id};\n";
}
DEMO: https://eval.in/57189
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed last month.
Improve this question
export function carBtnsMoveActive(boolean) {
const btnStart = document.querySelector('.btn-start')
const btnStop = document.querySelector('.btn-stop')
if (boolean) {
btnStart.disabled = false
btnStart.classList.remove('btn-off')
btnStop.disabled = true
btnStop.classList.add('btn-off')
} else {
btnStart.disabled = true
btnStart.classList.add('btn-off')
btnStop.disabled = false
btnStop.classList.remove('btn-off')
}
}
Hello, can someone help to improve and shrink down this 10 lines of code? I know this, IF can appearance better but i don't have knownledge how to do. I want to write readable code which has less lines. The code works.
I haven't tested this code, but this is my strategy for refactoring your code into something more concise.
function setEnabled(btn, isEnabled) {
btn.disabled = !isEnabled;
btn.classList[isEnabled ? 'remove' : 'add']('btn-off');
}
setEnabled(btnStart, !boolean)
setEnabled(btnStop, boolean)
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I have a similar use case to this
import { BehaviorSubject, combineLatest } from 'rxjs'
import { map, debounceTime } from 'rxjs/operators'
const items$ = new BehaviorSubject([]);
const size$ = new BehaviorSubject(10);
const visibleItems$ = combineLatest([items$, size$])
.pipe(
debounceTime(0),
map(([items, size]) => items.slice(0, size))
);
And some times I have this scenario
const onData = bigArr => {
items$.next(bigArr);
}
Sometimes this
const changeSize = () => {
size$.next(20);
}
And sometimes this
const onData2 = bigArr => {
items$.next(bigArr);
size$.next(10);
}
I don't want to trigger the visibleItems$ observable flow multiple times, so a solution that I've found is use the debounceTime operator with 0 ms to perform the onData2 method without running the pipe operators twice, but it is a bit hard to reason this operator (at least from the first glance). How can I replace it, so my code is easier to understand?
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
So my javascript class looks like this:
class Teams {
get myteams() {
return [
'Man utd',
'Barcelona'
]
}
constructor(){
return this
}
}
console.log(Array.from(new Teams()).join(','));
Without chanving the constructor, how can I print the content of the array in the function "myteams"?
Note that the constructor has to remain untouched. Also, I cannot add anything in the console.log. The changes need to be made inside the class.
Correct answer
Well, actually it was my fault not explaining it better. However, I found the solution, which was quite simple. Basically it was about declaring at the beginning pf the class this variable:
this = this.get;
Then it will be enough to only calling "new Teams" which will return the data from the getter method.
Try
console.log(new Teams().myteams.join(","));
You are trying to get an array from the actual Teams object, but the array only returned in the getter 'myteams', so you have to access that getter.
// -- Edit: For clarity sake --
You don't need to return anything in the constructor, in-fact you shouldn't.
class Teams {
get myteams() {
return [
'Man utd',
'Barcelona'
]
}
}
Would really be all you need to make the above code work.
Now do you want to be able to edit properties after construction like so:
class Teams {
constructor( teams ){
this.myteams = teams
}
}
const teams = new Teams( [ 'Man utd', 'Barcelona'] )
teams.myteams.push("FC Bacelona")
console.log( teams.myteams.join(", ") )
OR did you just mean you want an object literal that you can access and change at will: ( which could also be a getter )
const teams = {
myteams: ['Man utd', 'Barcelona']
}
const teams2 = {
get myteams(){
return [
'Man utd',
'Barcelona'
]
}
}
teams.myteams.push("FC Barcelona") // no error
console.log( teams.myteams.join(", ") ) // 'Man utd', Barcelona', 'FC Barcelona'
teams2.myteams.push("...") // throws error
// say you catch the above error, you fancy guy
console.log( teams2.myteams.join(", ") ) // 'Man utd', Barcelona', 'FC Barcelona'
Best of luck ( Sorry for hijacking your correct answer to explain on a wrongly closed question, it was my only recourse, good news, you'll get the credit)
I'm not sure why you're doing this but return this.myteams in your constructor should work.
your method myteams returns an array so your last line sould simply be console.log(new Teams());.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have two arrays:
sortKey: ["invoiceDate-desc", "invoiceDate-asc", "location-asc", "location-desc", "orderId-asc", "orderId-desc", "invoiceId-asc", "invoiceId-desc", "type-asc", "type-desc", "total-asc", "total-desc"]
and
receivedOrderKey: ["invoiceId", "orderId"]
I want to compare the above two arrays such that the result will contain all the values present in sortKey which matches partially with the values present in receivedOrderKey. For example: as receivedOrderKey contains invoiceId and orderId, the result should contain the following values from sortKey : "invoiceId-desc, "invoiceId-asc", "orderId-asc", "orderId-desc". I am presently using a two for loop solution to make this work. What would be an efficient way of doing this?
Code with for loops:
for(i=0;i<sortKey.length;i++){
var str1 = sortKey[i].toLowerCase();
for(j=0;j<receivedOrderKey.length;j++){
var str2 = receivedOrderKey[j].toLowerCase();
if(str1.includes(str2))
{
requestedOptions.push(sortKey[i]);
}
}
}
requestedOptions: ["orderId-asc", "orderId-desc", "invoiceId-asc", "invoiceId-desc"]
Use filter
sortKey.filter( s => receivedOrderKey.indexOf( s.replace(/\-(asc|desc)/, "") ) != -1 );
Demo
var sortKey = ["invoiceDate-desc", "invoiceDate-asc", "location-asc", "location-desc", "orderId-asc", "orderId-desc", "invoiceId-asc", "invoiceId-desc", "type-asc", "type-desc", "total-asc", "total-desc"];
var receivedOrderKey = ["invoiceId", "orderId", "status"];
var fnCheck = ( item ) => receivedOrderKey.indexOf( item.replace(/\-(asc|desc)/, "") ) != -1;
var output = sortKey.filter( s => fnCheck(s) );
console.log( output );
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have the following function
var label = function() {
return 'File: '+texts[t];
};
which is attached to highcharts, specified here
http://api.highcharts.com/highcharts#plotOptions.pie.dataLabels.formatter
where t has values let's say from 1 to 10 and text[t] corresponds to a different text. I attach this function to 10 highchart tooltips so that it executes the function with a mouseOver event.
The intended logic is that chart 1 has the text[1] label appearing, chart 6 has text[6], etc.
The problem is that all charts have the text[10] appearing, since t has that value when the function is executed.
How can I solve this? Is it a place for eval() like
var label = function() {
return 'File: '+eval(texts[t]);
};
UPDATE: based on comments, trying
var label = function(t) {
return 'File: '+t+' '+texts[t];
};
doesn't work as expected, it prints "File: [object Object] undefined"
This is a very common closure problem:
You probably have t in a for loop, just wrap the code which attaches the handler in another function:
// This will not work the way you might expect
// The value of i is left at 10 because that is the last
// time it is changed in the attacheHandlers1 scope held
// but the closure in the anonymous function used as a callback
// in setTimeout
//
function attachHandlers1(){
for(var i = 0; i < 10 ; i++){
setTimeout(function(){
console.log("Version 1", i);
}, 100)
}
}
// This works because the value is closured in
// attachHandlerImpl as 'x' with different values for
// each invocation
//
function attachHandlers2(){
for(var i = 0; i < 10 ; i++){
attachHandlerImpl(i);
}
}
function attachHandlerImpl(x){
setTimeout(function(){
console.log("Version 2", x);
}, 100);
}
attachHandlers1();
attachHandlers2();
Will output:
Version 1 10
Version 1 10
Version 1 10
Version 1 10
Version 1 10
Version 1 10
Version 1 10
Version 1 10
Version 1 10
Version 1 10
Version 2 0
Version 2 1
Version 2 2
Version 2 3
Version 2 4
Version 2 5
Version 2 6
Version 2 7
Version 2 8
Version 2 9
Without knowing the rest of your implementation details, something like this could work:
var texts = ['Text 1', 'Text 2', 'Text 3']
var label = function(idx) {
return "File: " + texts[idx];
};
label(2) returns "File: Text 3"