0

I have following problem: I make a cURL request and get a response like this (no json):

100
123456
Foo: Bar
Foo1: Bar1
Foo2: Bar2

To be able to work with that data, I create an array:

$result = preg_split("/\\r\\n|\\r|\\n/", $result);

Now I have an array with these items:

array(
    "100",
    "123456",
    "Foo: Bar",
    "Foo1: Bar1",
    "Foo2: Bar2"
)

My question is: Is there a nice way to create an array with key => value pairs, so the strings before the colons are the keys and the ones after the colons the values? The first two items never have colons, so I need to add a key to them separately and the string before the colons is never the same, so it isn't possible that there is the same key multiple times. Also, there's either just one or no colon.

Thanks in advance!

4
  • 1
    Can you give an example of what the result would look like? What should happen if a key is defined multiple times? What if the strings have zero or multiple colons? Commented Feb 5, 2018 at 22:50
  • Some of the items in your example have no colon. Commented Feb 5, 2018 at 22:51
  • Sorry, I forgot to mention that the strings before the colons never are the same, and there is always just one or no colon. Commented Feb 5, 2018 at 23:01
  • Information related to the question should be added to the question itself. Don't put in comments. Edit the question instead. Commented Feb 5, 2018 at 23:14

1 Answer 1

3

This code assumes that no keys are duplicates. If there are, the later one will overwrite the earlier. Entries that have no colon will use keys 0,1,2 etc.

$data = array(
    "100",
    "123456",
    "Foo: Bar",
    "Foo1: Bar1",
    "Foo2: Bar2"
);

$o = array_reduce($data, function($carry, $m){
    //echo $m . "\n";
    $e = explode(':', $m, 2);

    if ( count($e) == 1 ) {
        $carry[] = trim($e[0]);
    } else {
        $carry[$e[0]] = trim($e[1]);
    }
    return $carry;
}, []);

print_r($o);

Outputs:

Array
(
    [0] => 100
    [1] => 123456
    [Foo] =>  Bar
    [Foo1] =>  Bar1
    [Foo2] =>  Bar2
)
Sign up to request clarification or add additional context in comments.

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.