0

I have a string that looks like this:

$input_string = '<script>some data = 
{
    first: [[111,55],[123,66]],
    theColor: "#000000",
    second: [[111,95],[123,77]]
};
</script>'

As you can see, its a complex string, with some possible garbage, as well as two arrays mixed in. The arrays first dimension are the same in each array, ie, '111' and '123' - this should be the key to the new array created.

So I need to build new arrays, using that key/value pair and produce something like this for the first one:

array() {
    '111' =>
    array(2) {
        'first' => 
        string(2) "55"
        'second' =>
        string(2) "95"
    }
}
3
  • 1
    I don't get it! be more clear!! Commented Jun 4, 2015 at 7:47
  • If you show us more code, we might be able to show better solution for the task you are trying to do Commented Jun 4, 2015 at 7:52
  • sorry, but literally this is all I have been given - I need to be clear on any assumptions I make when providing the solution. I'm kinda glad others are finding it hard too and not just me :) Commented Jun 4, 2015 at 8:07

1 Answer 1

1

I used Regex in order to extract key and values in 2 separated arrays.

See Demo.

<?php

$re = "/(\\[?(?:\\[(\\d{1,}),(\\d{1,})\\]))/"; 
$str = '<script>some data = 
{
first: [[111,55],[123,66]],
theColor: "#000000",
second: [[111,95],[123,77]]
};
</script>'; 

preg_match_all($re, $str, $matches);

$output = array();

for($i = 0; $i < count($matches); ++$i)
{
    // If Key already exists - We push
    if(isset($output[($matches[2][$i])]))
        array_push($output[($matches[2][$i])], $matches[3][$i]);

    // Otherwise we create an array to store possible future values.
    else
        $output[($matches[2][$i])] = array( 0 => $matches[3][$i]);
}

print "<pre>";
print_r($output);
print "</pre>";


?>

OUTPUT :

Array
(
[111] => Array
    (
        [0] => 55
        [1] => 95
    )

[123] => Array
    (
        [0] => 66
        [1] => 77
    )

)

Ezy Pezy Lemon Squizzy.

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

5 Comments

Cello powaa! If my code fits the result you can fill my post as answer.
OK so here's the thing - u have added newlines into the original string - I am NOT allowed to modify the string itself other than via code :) Are they necessary for the solution ? I am not great with regex
U have to escape the input string with mysql_real_escape_string() - There are some non escaped " characters inside of it. After escaped it - Edit your post and give me the real string input declaration if it doesn't work.
sorry, still testing things, the output wasn't quite wot i expected. Will come back soon

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.