0

How can I parse a string of the following format into an associative array?

[ ["key1", "value1"], ["key2", "value2"], ["key3", "value3] ]

Into:

Array
(
    ["key1"] => "value1"
    ["key2"] => "value2"
    ["key3"] => "value3"
)

Thanks!

edit: The data is in a string format i.e:

$stringdata ='[ ["key1", "value1"], ["key2", "value2"], ["key3", "value3"] ]';

3 Answers 3

1

Use a loop and loop through the whole array and assign your values into a new array using the first element as key and the second element as value. Usually like this:

$new_array = array();
foreach($array as $arr) {
    $new_array[$arr[0]] = $arr[1];
}

But to parse the string into an array I would take the following RegEx approach and then a loop:

$str = '[ ["key1", "value1"], ["key2", "value2"], ["key3", "value3"] ]';
preg_match_all('/(\[("(.*?)"), ("(.*?)")\])/i', $str, $matches);
//Now we have in $matches[3] and $matches[5] the keys and the values
//and we would now turn this into an array using a loop

$new_array = array();
for($k = 0; $k < count($matches[3]); $k++) {
    $new_array[$matches[3][$k]] = $matches[5][$k];
}

See this live demo https://3v4l.org/u3jpl

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

Comments

0

Use functional approach with array_reduce

<?php
$ar = [ ["key1", "value1"], ["key2", "value2"], ["key3", "value3"] ];
$newAr = array_reduce($ar, function($carry, $item) {
    $carry[$item[0]] = $item[1];
    return $carry;
});

var_dump($newAr);

Output:

array(3) {
  ["key1"]=>
  string(6) "value1"
  ["key2"]=>
  string(6) "value2"
  ["key3"]=>
  string(6) "value3"
}

Comments

0

Here is a solution using json_decode.

<?php

$json = json_decode('[["key1", "value1"], ["key2", "value2"], ["key3", "value3"]]');

$final = array();
foreach($json as $value) {  
    $final[] = array($value[0]=>$value[1]);
}

final is the array in your required format.

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.