1

I'm getting this string which I can't control:

$string = '[{"val":"agent,,james,,89","number":0,"dID":0}, {"val":"house,,Villa,,389m","number":1,"dID":2}]';

Would like to only collect the val and put them into an array where they are separated by the two commas

End results:

var_dump($resArr) // Array [{"agent", "james", "89"}, {"house", "villa", "389m"}]

What I've done so far:

$string = '[{"val":"agent,,james,,89","number":0,"dID":0}, {"val":"house,,Villa,,389m","number":1,"dID":2}]';

parse_str(stripslashes(str_replace(["'=>'","','"],['=','&'],trim($string,"'"))),$form_data);

var_dump($form_data);

2 Answers 2

1

Since your initial string is JSON, you can easily parse it with json_decode(). Then just iterate through the array and explode() the "val" by the delimiter ,, and add it to an array.

<?php

$string = '[{"val":"agent,,james,,89","number":0,"dID":0}, {"val":"house,,Villa,,389m","number":1,"dID":2}]';

$json = json_decode($string, true);
$output = [];
foreach($json as $elm)
{
    $val = $elm["val"];
    $words = explode(",,", $val);
    $output[] = $words;
}

var_dump($output);
?>

This gives $output a value of

[["agent", "james", "89"], ["house", "villa", "389m"]]

Demo here

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

Comments

0

You have an accepted answer, but I was bored:

$result = array_map(function($v) {
                        return explode(',,', $v['val']);
                    }, json_decode($string, true));

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.