Tutorial :Can I divide an array or string into multiple variables?



Question:

Here's where I've been:
I made a PHP client call via soap to retrieve an array of data,
I successfully receieved and converted my array to JSON via json_encode,
I then echoed it back to my page.

Here's where I am:
I get back my array in this format...
{"MethodName":"ID,11|1|Item1,22|2|Item2,33|3|Item3"}

Here's where I want to be:
Using Javascript or JSON, my objective is to end up with 2 variables (Method & ID) and one variable array (ItemList)...ie

  • var Method = "MethodName";
  • var ID = "ID";
  • var ItemList = ['11|1|Item1' , '22|2|Item2' , '33|3|Item3'];

I have the front and back of my script working, but I'm stumped on the array(string)...
How do I parse, divide, or split this result?


Solution:1

i'd probably try a regex first thing. something like

var match = data.match(/\{"(.+)"\:"([^,]+),(.+)"\}/);  

the parentheses will separate the matches. match[0] will be the whole thing, match[1] will be the method name, match[2] will be the id, match[3] will be the remainder as a string. you can then do

var itemList = match[3].split(',');  

to get the array for the 3rd part.


Solution:2

You would make this much simpler on yourself if you had it as a mixed array in php before you called json_encode (so that instead of a string, each item would be it's own JSON object).

Example:

$arr = array();  $itemList = array();  $itemList[1] = "11|1";  $itemList[2] = "22|2";  $itemList[3] = "33|3";    $arr['Method']="MethodName";  $arr['ID']= "ID";  $arr['itemList'] = $itemList;    $output = json_encode($arr);  

This results in $output having the following JSON:

{"Method":"MethodName","ID":"ID","itemList":{"1":"11|1","2":"22|2","3":"33|3"}}  

Which you can then easily pull out, as the itemList is an array in JSON already.


Solution:3

Let's say your intial array is initial_array with value {"MethodName":"ID,11|1|Item1,22|2|Item2,33|3|Item3"}

for (key in initial_array) {      Method = key;                     // Method = "MethodName"    break;  }  myvalue = initial_array[Method];  myarray = myvalue.split(",");      // myarray = ["ID","11|1|Item1",...]  ID = myarray[0];                   // ID = "ID"  ItemList = myarray.splice(1);      // ItemList = ["11|1|Item1","22|2|Item2",...]   


Solution:4

Here you go:

var myobject = {"MethodName":"ID,11|1|Item1,22|2|Item2,33|3|Item3"};  var itemlist = [];  var method;  var ID;    for (key in myobject) {       method = key;      break;  }    itemlist = myobject[method].split(',');  ID = itemlist.shift();  

Here is a JSFiddle for you to run.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »