Explode a String to Associative Array Without Using Loops

Explode a string to associative array without using loops?

Here's a way to do it without a for loop, using array_walk:

$array = explode(',', $string);
$new_array = array();
array_walk($array,'walk', $new_array);

function walk($val, $key, &$new_array){
$nums = explode('-',$val);
$new_array[$nums[0]] = $nums[1];
}

Example on Ideone.com.

PHP - Using explode() function to assign values to an associative array

I would use array_combine like so:

$fields = array ( 'first_name', 'last_name' );
$arr = array_combine ( $fields, explode ( " ", $str ) );

EDIT: I would also pick this over using list() since it allows you to add fields should you require without making the list() call unnecessarily long.

How can I convert an array of strings into an associative array in PHP?

As simple as:

$arr = array(
"action: Added; amount: 1; code: RNA1; name: Mens Organic T-shirt; colour: White; size: XL",
"action: Subtracted; amount: 7; code: RNC1; name: Kids Basic T-shirt; colour: Denim Blue; size: 3-4y",
"action: Added; amount: 20; code: RNV1; name: Gift Voucher; style: Mens; value: £20",
);

$data = [];
foreach ($arr as $line) {
$newItem = [];
foreach (explode(';', $line) as $item) {
$parts = explode(':', $item);
$newItem[trim($parts[0])] = trim($parts[1]);
}
$data[] = $newItem;
}

print_r($data);

Fiddle here.

Convert key/value string into associative array

You can just explode() your string first on a space and then with array_map() each value on a colon. After that just use array_column() to get the keys and values into place:

$result = array_column(array_map(function($v){
return explode(":", $v);
}, explode(" ", $str)), 1, 0);

You can also do it with a regex as you started and use named capturing groups, e.g.

preg_match_all("/(?P<keys>\w+):(?P<values>[\w@]+)/", $str, $m);
$result = array_combine($m["keys"], $m["values"]);

How to split string into an associative array which has arrays within arrays

You can user parse_str() and explode() functions to achieve this.

Steps:

1) Use parse_str() function, it will split your string into associative array.

2) Now loop over it and go for key values.

3) keys will be the required keys (names, age and fav-nums) and you want values to be array.

4) explode() the values with ; and you will get required values.

Working code:

$str = "names=bob;mike;sam&age=30;23;22&fav-nums=200;300;400";
parse_str($str, $output);
$arr = [];
if (! empty($output)) {
foreach ($output as $key => $value) {
$arr[$key] = explode(';', $value);
}
}
echo '<pre>';print_r($arr);echo '</pre>';

Output:

Array
(
[names] => Array
(
[0] => bob
[1] => mike
[2] => sam
)

[age] => Array
(
[0] => 30
[1] => 23
[2] => 22
)

[fav-nums] => Array
(
[0] => 200
[1] => 300
[2] => 400
)

)

Bash: Split two strings directly into associative array

A (somewhat convoluted) variation on @accdias's answer of assigning the values via the declare -A command, but will need a bit of explanation for each step ...

First we need to break the 2 variables into separate lines for each item:

$ echo "${firstString}" | tr "${delimiter}" '\n'
00011010
00011101
00100001

$ echo "${secondString}" | tr "${delimiter}" '\n'
H
K
O

What's nice about this is that we can now process these 2 sets of key/value pairs as separate files.

NOTE: For the rest off this discussion I'm going to replace "${delimiter}" with ':' to make this a tad bit (but not much) less convoluted.

Next we make use of the paste command to merge our 2 'files' into a single file; we'll also designate ']' as the delimiter between key/value mappings:

$ paste -d ']' <(echo "${firstString}" | tr ':' '\n') <(echo "${secondString}" | tr ':' '\n')
00011010]H
00011101]K
00100001]O

We'll now run these results through a couple sed patterns to build our array assignments:

$ paste -d ']' <(echo "${firstString}" | tr ':' '\n') <(echo "${secondString}" | tr ':' '\n') | sed 's/^/[/g;s/]/]=/g'
[00011010]=H
[00011101]=K
[00100001]=O

What we'd like to do now is use this output in the typeset -A command but unfortunately we need to build the entire command and then eval it:

$ evalstring="typeset -A kv=( "$(paste -d ']' <(echo "${firstString}" | tr ':' '\n') <(echo "${secondString}" | tr ':' '\n') | sed 's/^/[/g;s/]/]=/g')" )"

$ echo "$evalstring"
typeset -A kv=( [00011010]=H
[00011101]=K
[00100001]=O )

If we want to remove the carriage returns and put on a single line we append another tr at the output from the sed command:

$ evalstring="typeset -A kv=( "$(paste -d ']' <(echo "${firstString}" | tr ':' '\n') <(echo "${secondString}" | tr ':' '\n') | sed 's/^/[/g;s/]/]=/g' | tr '\n' ' ')" )"

$ cat "${evalstring}"
typeset -A kv=( [00011010]=H [00011101]=K [00100001]=O )

At this point we can eval our auto-generated typeset -A command:

$ eval "${evalstring}"

And now loop through our array displaying the key/value pairs:

$ for i in ${!kv[@]}; do echo "kv[${i}] = ${kv[${i}]}"; done
kv[00011010] = H
kv[00100001] = O
kv[00011101] = K

Hey, I did say this would be a bit convoluted! :-)

How to explode string into array with index in php?

try this code:

$str = "var1,'Hello'|var2,'World'|";
$sub_str = explode("|", $str);
$array = [];
foreach ($sub_str as $string) {
$data = explode(',', $string);
if(isset($data[0]) && !empty($data[0])){
$array[$data[0]] = $data[1];
}
}

How to get an associative array from a string?

You can use the limit parameter of preg_split to make it only split the string once

http://php.net/manual/en/function.preg-split.php

you should change

$result = preg_split ('/=/', $val);

to

$result = preg_split ('/=/', $val, 2);

Hope this helps



Related Topics



Leave a reply



Submit