PHP - Make Multi-Dimensional Associative Array from a Delimited String

Build and fill multi-dimensional associative array from many delimited strings

Not sure what problems you were running into, but the following works ok. See https://eval.in/636072 for a demo.

$result = [];

// Each item in $source represents a new value in the resulting array
foreach ($source as $item) {
$keys = explode('.', $item['path']);

// Initialise current target to the top level of the array at each step
$target = &$result;

// Loop over each piece of the key, drilling deeper into the final array
foreach ($keys as $key) {
$target = &$target[$key];
}

// When the keys are exhausted, assign the value to the target
$target = $item['value'];
}

PHP - Make multi-dimensional associative array from a delimited string

What have you tried? The absolute answer to this is very easy:

$keys = explode('.', $string);
$array = array();
$arr = &$array;
foreach ($keys as $key) {
$arr[$key] = array();
$arr = &$arr[$key];
}
unset($arr);

...but why would this be useful to you?

Create multidimensional associative array from a string

Since it's a valid array definition in PHP you can eval it as PHP code:

eval("\$myVar3 = array($myVar2);");
print_r($myVar3);

Or transform it into JSON and decode it. Might be easier but I got this to work:

$myVar2 = str_replace(["'", '=>', '[', ']'], ['"', ':', '{', '}'], $myVar2);
$myVar3 = json_decode('{'.$myVar2.'}', true);
print_r($myVar3);

But if you are creating/storing this, then you would be better off just storing JSON in the fist place.

PHP make a multidimensional associative array from key names

I'll try to explain it for you to understand it a little better, see the working code here. I hope it helps you understand this $curr = &$curr[$key]; line. $curr points to the empty $arr before the foreach starts, In foreach it saves the value of $key into the $arr by reference which was pointed by $curr and then reassigns the reference of the newly saved $key in $arr to the $curr pointer again.

// initialize variables
$val = 'it works !';
$arr = [];

// Get the keys we want to assign
$keys = [ 'key_1', 'key_2', 'key_3', 'key_4' ];

// Get a reference to where we start
echo "create a space where to save the first key \r\n";
$curr = &$arr;

// Loops over keys
$i = 1;
foreach($keys as $key) {

echo "**************** Iteration no $i ******************\r\n";
// echo "save the value \"$key\" to the reference created earlier in the \$curr variable for the empty array above where the kesy are actually being saved \r\n";

// get the reference for this key
echo "Now save the value of \$key to the array reference present in \$curr and then assigne the reference of newly saved array item to \$curr again \r\n";
$curr = &$curr[$key];
print_r($arr);

$i++;
echo "\r\n\r\n";
}

// Assign the value to our last reference
$curr = $val;

// visualize the output, so we know its right
print_r($arr);

Split and parse a string to create an array of associative arrays

For a new contributor, a solution with foreach is easier to understand in my opinion.
The steps are commented in the code.

$coordinates = "9.499819 123.920318,9.490845 123.916563,9.484644 123.922292,9.49148 123.931519,9.499755 123.925683,9.499819 123.920318";

$polygon = explode(',',$coordinates);
/*
array (
0 => "9.499819 123.920318",
1 => "9.490845 123.916563",
*/

foreach($polygon as $index => $latLng){
//The element $latLng is split into two variables with list and explode.
list($lat,$lng) = explode(' ',$latLng);

//The elements are replaced by a new array with the variables $lat and $lng as float
$polygon[$index] = ['lat' => (float)$lat, 'lng' => (float)$lng];
}

//test output
echo '<pre>';
var_export($polygon);

output:

array (
0 =>
array (
'lat' => 9.499819,
'lng' => 123.920318,
),
1 =>
array (
'lat' => 9.490845,
'lng' => 123.916563,
),
2 =>
array (
'lat' => 9.484644,
'lng' => 123.922292,
),
3 =>
array (
'lat' => 9.49148,
'lng' => 123.931519,
),
4 =>
array (
'lat' => 9.499755,
'lng' => 123.925683,
),
5 =>
array (
'lat' => 9.499819,
'lng' => 123.920318,
),
)

Add 2022-03-04:

This one-liner with preg_match_all already returns the complete result, but with additional numeric keys.

preg_match_all('~(?<lat>[0-9.]+) (?<lng>[0-9.]+),?~', $coordinates, $match,PREG_SET_ORDER);

array_map can be used to remove the superfluous values.

$polygon = array_map(
function($row){return ['lat' => $row['lat'],'lng' => $row['lng']];},
$match
);

Converting a string into a multi-dimensional array with commas and pipes

I wouldn't even bother with looking for | or manually traversing anything. You can generate the desired array already with preg_match_all containing just a few fillers:

preg_match_all(
"/(?<sku>\w+),(?<qty>\d+)\K/",
$string, $array, PREG_SET_ORDER
);

This simply extracts any combination of alphanumeric \w+ and numeric \d+ entries delimited by , comma.

Convert string with no delimiters into associative multidimensional array

Use the PREG_SPLIT_DELIM_CAPTURE flag of the preg_split function to also get the captured delimiter (see documentation).

So in your case:

# The -1 is the limit parameter (no limit)
$attributes = preg_split('/(\*[A-Z0-9]{2})/', $line, -1, PREG_SPLIT_DELIM_CAPTURE);

Now you have element 0 of $attributes as everything before the first delimiter and then alternating the captured delimiter and the next group so you can build your $matches array like this (assuming that you do not want to keep the first group):

for($i=1; $i<sizeof($attributes)-1; $i+=2){
$matches[$attributes[$i]] = $attributes[$i+1];
}

In order to account for delimiters being present multiple times you can adjust the line inside the for loop to check whether this key already exists and in that case create an array.

Edit: a possibility to create an array if necessary is to use this code:

for($i=1; $i<sizeof($attributes)-1; $i+=2){
$key = $attributes[$i];
if(array_key_exists($key, $matches)){
if(!is_array($matches[$key]){
$matches[$key] = [$matches[$key]];
}
array_push($matches[$key], $attributes[$i+1]);
} else {
$matches[$attributes[$i]] = $attributes[$i+1];
}
}

The downstream code can certainly be simplified, especially if you put all values in (possibly single element) arrays.

How to convert PHP multidimensional associative array to API http query in the format the API specifies?

The project parameter is JSON in their example, so use json_encode() to create that.

$folder_data = array(
"title" => "Testing API Creation",
"description" => "Testing the Wrike API by creating this folder.",
"project" => json_encode(array(
"status" => "OnHold",
"startDate" => "2022-05-19",
"endDate" => "2022-06-19",
"contractType" => "Billable",
"budget" => 100
))
);


Related Topics



Leave a reply



Submit