0

I have a string of numbers separated by : like "20:1:21,21:0:21", this php code explodes the strings with , and and concatenate the resulting arrays into an associative array like:

$in = "20:1:21,21:0:21";
$list=explode(",",$in);
$results = array( 0 => array(), 1 => array());
foreach ($list as $item) {
        $item=explode(":",$item);
        if (sizeof($item)==3) {
            $results[$item[1]][$item[0]] += $item[2];
        }
    }

note the += operator here.

The expected value of

array(2) {
  [0]=>
  array(1) {
    [21]=>
    int(21)
  }
  [1]=>
  array(1) {
    [20]=>
    int(21)
  }
}

or [{"21":21},{"20":21}] as json output.

In javascript it could be like

    var results = { 0: [], 1: [] };
    for (var key in list) {
        var item = list[key];
        item=item.split(":");
        if (item.length == 3) {
            if(!results[item[1]]) results[item[1]]={};
            results[item[1]][item[0]]=item[2];
        }
    }

but it creates a list of null values before appending the right values, why?

12
  • 1
    Please show us the expected output and the output you're getting. You should also show us what the $in variable contains. Commented Feb 19, 2019 at 13:35
  • You say you have a string, but then show code where apparently you have an array (list). Which is it? Please provide samples of the input (in JS format), the expected output for it and what you get. Commented Feb 19, 2019 at 13:36
  • 1
    “note the += operator here” - note how you did something completely different in your JS … Commented Feb 19, 2019 at 13:40
  • 1
    If you replace += with = it will produce the results you want. Commented Feb 19, 2019 at 13:41
  • 1
    Data types are not completely comparable between PHP and JS. Associative arrays with numerical indexes translate best to JS arrays. Commented Feb 19, 2019 at 13:46

2 Answers 2

3

Your JS code seems to expect an array as input, but your input is a string. Also, you define result as a plain object, but really want an array...

Here is how you can do it in JavaScript.

var input = "20:1:21,21:0:21";

var result = input.split(",")
     .map(s => s.split(":"))
     .reduce((acc, [a,b,c]) => (acc[b] = {[a]: c}, acc), []);

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

1

Or you can use Regex to accomplish it:

var string = '20:1:21,21:0:21';
var regex = /(\d+):(\d+):(\d+)/g;
var match;
var result = {};

while (match = regex.exec(string)) {
    result[match[2]] = {[match[1]]: match[3]};
}

console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.