How to convert Array to JSON

need your help about this one…
how can i convert this arrays to json code…

here’s my code:

$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);

// Will dump a beauty json :3
var_dump(json_decode($result, true));

$result = file_get_contents($url);
// Will dump a beauty json :3
var_dump(json_decode($result, true));

enter image description here


Source: stackoverflow-php

Javascript function. What is missing?

Write a program to find count of the most frequent item of an array.

Assume that input is array of integers.

Ex.:

input array: [3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3]
ouptut: 5
Most frequent number in example array is -1. It occurs 5 times in input array.

Here is my code:
function mostFrequentItemCount(collection) {

var copy = collection.slice(0);

for (var i = 0; i < collection.length; i++) {
 var output = 0;
 for (var x = 0; x < copy.length; x++) {
   if (collection[i] == copy[x]) {
 output++; 
}
}
}
  return output; 
 }

It seems to be just counting the reoccurrence of the first number in the array not the one that occurs the most. I can’t figure out how to make it count the most occurring one.


Source: stackoverflow-javascript

RxJS update Observable array items on the fly

Im using GeoFire in an Ionic 2/Firebase APP. The main screen function gets all the users that are close by as follows, This gets fed to an ngFor loop as an array.

The issue: If one of the users details change, for instance if they change their name, then a duplicate user gets added to the array rather than the actual user getting updated. Im not sure how to work this into this function.

public outputUsersCloseToMe() : Observable<Array<displayAllUsers>> {

    const currUsr = this.firebaseInit().auth().currentUser.uid

    let availableUsers = <Array<displayAllUsers>>[];

    const loc = this.firebaseInit().database().ref("users")
                                .child(currUsr)
                                .child('profile')
                                .child('lastKnownLocation');

    loc.once('value').then( (snapshot) => {
        let geoQuery = this.geoFire.query({
            center: [snapshot.val().lat, snapshot.val().lng],
            radius: 12.0//kilometers
        });
        geoQuery.on("key_entered", (key, location, distance) => {
            this.firebaseInit().database().ref('users').child(key).child('profile').on('value', (userprofile) => {  
                if( userprofile.val() ) {
                    availableUsers.push({ 
                        id: userprofile.val().id,                        
                        gender: userprofile.val().gender,
                        distance: distance.toFixed(2),
                        location: location,
                        firstName: userprofile.val().firstName,                        
                    });        
                }
            }); 
        });
    });
    return Observable.from([availableUsers]).map(val => val); 
}

and the template is similar to the following

        
{{ usr?.id }}


Source: stackoverflow-javascript

Sort JavaScript array by 3 values

I’d like to sort this JavaScript array by three values, but I can’t seem to figure out how to sort by more than one property at a time.

The requirements are:

  1. featured items should be at the very top
  2. Then items with no name (null)
  3. Then items with a name that are not featured
  4. Sort everything by createdAt in descending order (newest first)

This is the array:

var items [
    { name: 'foo-1', featured: true,  createdAt: 1493000001 },
    { name: null,    featured: false, createdAt: 1493000003 },
    { name: 'foo-3', featured: true,  createdAt: 1493000002 },
    { name: 'foo-4', featured: false, createdAt: 1493000004 },
    { name: 'foo-5', featured: false, createdAt: 1493000005 },
];

The result should be:

[
    { name: 'foo-3', featured: true,  createdAt: 1493000002 },
    { name: 'foo-1', featured: true,  createdAt: 1493000001 },
    { name: null,    featured: false, createdAt: 1493000003 },
    { name: 'foo-5', featured: false, createdAt: 1493000005 },
    { name: 'foo-4', featured: false, createdAt: 1493000004 },
]


Source: stackoverflow-javascript

pass array values from AJAx to PHP

Hi i am facing some issues. I am trying to insert array in mysql using ajax and php but its not working following is my code:

HTML:

 <input type="text" class="form-control" name="invoice" id="invoice"   placeholder="piece">
 <input type="text" class="form-control" name="pieces[]" id="pieces" placeholder="Qty">

i want to pass fields from ajax to php. I am using following code in ajax.

var inv = $("#invoice").val();
var pieces = $("#pieces").val();

$.ajax({

    type: "POST",
    url: "query.php",
    data: "piece="+pieces+"&inv="+inv,
    success: function(data){

        $("#result").html(data);
    }

});

following is the PHP code.

<?php
$piece = $_POST[piece];
foreach ($piece as $key=>$value)
{
$query = mysql_query(insert into items values ('$value','$_POST[inv]');
}
?>


Source: stackoverflow-php

Uncaught TypeError: Cannot set property ‘todoText’ of undefined

Working on the Javascript objects and functions. Facing issue with it.

  var todoList = {
      todo:[],
      displayTodo:function(){
        console.log('My Todo:',this.todo); 
      },
      addTodo:function(todoText){
        this.todo.push({
          todoText:todoText,
          complete:false
        });
        this.displayTodo();
      },
      changeTodo:function(posi,newTodo){
        //this.todo[posi] = newTodo; 
        this.todo[posi].todoText=newTodo;
        this.displayTodo();
      },
      toggleComplte:function(posi){
        var todo = this.todo[posi];
        todo.complete = !todo.complete;
        this.displayTodo();
      }
    }


    todoList.toggleComplte(0)

Error I got when running.

VM1196:16 Uncaught TypeError: Cannot set property 'todoText' of undefined
    at Object.changeTodo (<anonymous>:16:29)
    at <anonymous>:21:10

Can some one suggest what is the error ?


Source: stackoverflow-javascript

Is it possible to write a return array in If clause

I have a code for my website where i want certain usergroups to view certain files/filesextensions.
i have defined all prefererences in a return array and then simply made two of them, showing one if usergroup equals (eg $k=1), showing two if usergroup equals $k2.

but it does not work and i dont know why… any ideas? this is my code below..
thanks for your help in advance!

$k=1,2,3 depending on premium user level

if ($k==1) {

  return array(

    // Basic settings
    'hide_dot_files'            => true,
    'list_folders_first'        => true,
    'list_sort_order'           => 'natcasesort',
    'theme_name'                => 'bootstrap',
    'external_links_new_window' => true,
    // Hidden files
    'hidden_files' => array(
        '.ht*',
        '*/.ht*',
        'resources',
        'resources/*',
        'analytics.inc',
        'header.php',
		'cont.php',
		 'shoutbox.php',
		  'userinfo.php',
		  'stats.php',
		  'stats.html',
        'footer.php',
		'phpSecurePages/*',
		'phpSecurePages',
		'uploadify',
		        '*.docx',
		'*.pdf',
		'*.jpg',
		'*.jpeg',
		'*.doc',
		'*.PDF',
		'*.JPG',
		'*.JPEG',
		'*.DOC',
    etc

); 
      } else 
      { 
      return array(

    // Basic settings
    'hide_dot_files'            => true,
    'list_folders_first'        => true,
    'list_sort_order'           => 'natcasesort',
    'theme_name'                => 'bootstrap',
    'external_links_new_window' => true,
    // Hidden files
    'hidden_files' => array(
        '.ht*',
        '*/.ht*',
        'resources',
        'resources/*',
        'analytics.inc',
        'header.php',
		'cont.php',
		 'shoutbox.php',
		  'userinfo.php',
		  'stats.php',
		  'stats.html',
        'footer.php',
		'phpSecurePages/*',
		'phpSecurePages',
		'uploadify',
); }


Source: stackoverflow-php

String to Object with JavaScript

I would like to know the most efficient way to convert this string into an object in JavaScript.

This is the ugly string:

  ""date","initRegistrations","registrations","finalizeRegistrations"rn"03/29/2017","0","0","0"rn"03/30/2017","5","4","4"rn"03/31/2017","42","0","0"rn"04/01/2017","192","0","0"rn"04/02/2017","4","0","0"rn"04/03/2017","23","0","0"rn"04/04/2017","5","0","0"rn"

At the moment I’m using this function, but it does not work fine, the expected output would be a object of object with the keys date, initRegistrations, registrations, finalizeRegistrations:

   function convertToArrayOfObjects(data) {
    var keys = data.shift(),
        i = 0, k = 0,
        obj = null,
        output = [];

    for (i = 0; i < data.length; i++) {
        obj = {};

        for (k = 0; k < keys.length; k++) {
          if(data[i][k]){
            obj[keys[k]] = data[i][k];
          }

        }

        output.push(obj);
    }

    return output;
}

Is there any fancy way to achieve this easily or I should go playing with my array of objects?
Any help or advice is appreciated.
Thanks.


Source: stackoverflow-javascript

Closing Tags After Last Row

In a function, there is a foreach loop that is calling up another function to pull out secondary notes and sublists to append to the main data. It all works except for one part where there is a sublist, I cannot seem to make it close the tags. This is what I have but perhaps there is some other way?

global $rowCount;

$rowCount++;
$Count = array($rowCount);

foreach ($Count as $key => $a) :
   if (end($Count) == $a) :
       // Close the subtable after last row
       $NotesText .= "</div>nn";
       // Restart row table
       $NotesText .= "<div id="css-table">n";
   endif;
endforeach;

Using print_r($Count) the array looks something like this and I’m not an expert at arrays but it appears that it is creating individual arrays, one for each line:

Array ( [0] => 1 )
Array ( [0] => 2 )
Array ( [0] => 3 )
Array ( [0] => 4 )
Array ( [0] => 5 )
Array ( [0] => 6 )
Array ( [0] => 7 )
Array ( [0] => 8 )
Array ( [0] => 9 )
Array ( [0] => 10 )
Array ( [0] => 11 )
Array ( [0] => 12 )
Array ( [0] => 13 )
Array ( [0] => 14 )


Source: stackoverflow-php