1

Sorry about the pretty bad title, I'm not a native speaker and wasn't sure how to phrase this.

Here is my problem:

I have a very long array with this format:

$array = array(
    'key1.value1' => '1',
    'key1.value2' => '0',
    'key1.value3' => '1',
    'key2.value1' => '0',
    'key2.value2' => '0',
    'key3.value1' => '1'
);

From this array, I would like to get another one with this format:

$newArray = array(
   'key1' => array(
        'value1' => '1',
        'value2' => '0',
        'value3' => '1'
    ),
    'key2' => array(
        'value1' => '0',
        'value2' => '0'
    ),
    'key3' => array(
        'value1' => '1'
    )
);

I have tried a few methods but really didn't find any solution that isn't extremely long, so I wondered if I could any tips/tricks to get this done easily!

Thanks a lot!

1
  • you can try to use in_array(string, $array); Commented Feb 3, 2017 at 11:08

3 Answers 3

1
$array = array(
    'key1.value1' => '1',
    'key1.value2' => '0',
    'key1.value3' => '1',
    'key2.value1' => '0',
    'key2.value2' => '0',
    'key3.value1' => '1'
);

$Results = array();
foreach($array as $key=>$value){
    $KeyValue = explode(".",$key);
    if(!isset($Results[$KeyValue[0]])){
        $Results[$KeyValue[0]] = array();
    }
    $Results[$KeyValue[0]][end($KeyValue)] = $value;
}
print_r($Results);
Sign up to request clarification or add additional context in comments.

3 Comments

i've see that only create a 1 second level?. Could be?
@Álvaro Touzón this should give the chap the format he needs.
Works perfectly! Thanks a lot!
0

Short solution using explode() function:

$transformed = [];
foreach ($array as $k => $v) {
    $pair = explode('.', $k);
    $transformed[$pair[0]][$pair[1]] = $v;
}

print_r($transformed);

The output:

Array
(
    [key1] => Array
        (
            [value1] => 1
            [value2] => 0
            [value3] => 1
        )

    [key2] => Array
        (
            [value1] => 0
            [value2] => 0
        )

    [key3] => Array
        (
            [value1] => 1
        )
)

Comments

0

try this:

$generate = [];
foreach($array  as $key=>$val ){
list($first, $second) = split('.', $key);
if(!isset($genrate[$first]){
$genrate[$first] = [];
if(!$genrate[$first][$second]){
$genrate[$first][$second]= [];
}
}
$genrate[$first][$second] = $val;
}

Expect it helps. Tks

1 Comment

$val or $value needs to change

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.