Home > Mobile >  Converting a string with breaking points to array
Converting a string with breaking points to array

Time:12-10

I have a JavaScript AJAX linked with PHP. The PHP has this code:

while ($row = $req->fetch(PDO::FETCH_BOTH)) {
    $ajaxArray[] = $row[0];
    $ajaxArray[] = $row[1];
    $ajaxArray[] = $row[2];
    $ajaxArray[] = $row[3];
}

foreach ($ajaxArray as $val) {
    echo $val;
    echo "#";
}

and the output of it will be a string:

Three Guys Burger Spicy#2#Three guys burger tender, juicy, full of flavor, served with bbq sauce mixed with special sauce#Burger1.PNG#

I want to create a JavaScript array with these elements:

['Three Guys Burger Spicy', 2, 'Three guys burger tender, juicy, full of flavor, served with bbq sauce mixed with special sauce', 'Burger1.PNG']

is there a predefined function to use? Do you have a solution for this?

CodePudding user response:

A much simpler approach would be to just encode the array as JSON - that will produce you the result you want without any extra string-building and string-parsing.

echo json_encode($ajaxArray);

All you have to do on the JavaScript side when you receive that is parse the JSON (using JSON.parse(), normally), and then you'll have a JavaScript array ready to go.

N.B. Based on what you've shown, it appears you're only expecting one row to be returned from the query. If so, you can shorten the code which populates the array, as well:

if ($row = $req->fetch(PDO::FETCH_NUM)) {
    $ajaxArray = $row;
}

Documentation references:

CodePudding user response:

const str = 'Three Guys Burger Spicy#2#Three guys burger tender, juicy, full of flavor, served with bbq sauce mixed with special sauce#Burger1.PNG#';

const arr = str.split('#').filter(v => v);

console.log( arr );

CodePudding user response:

You can split the string by "#":

var output = "#Three Guys Burger Spicy#2#Three guys burger tender, juicy, full of flavor, served with bbq sauce mixed with special sauce#Burger1.PNG#";

// Remove any trailing/leading hashes
output = output.replace(/^#/, "").replace(/#$/, "");

// Split on "#", then convert any numeric entries to numbers
var arr = output.split("#").map(item => !isNaN(Number(item)) ? Number(item) : item);
console.log(arr);

  • Related