문제

I'm working with dynamic data, so I'm trying to put that data into a bidimensional array.

I need a structure like this:

$array['something1'] = array ( 'hi1' => 'there1' , 'hi2' => 'there2' );

All this data is dynamically generated by a foreach, ex.:

$list = array ( 0 => 'something;hi1;there1' , 1 => 'something;hi2;there2' );


foreach ( $list as $key => $data )
{
    // extract data
    $columns    = explode ( ';' , $data );

    // set data
    $items[$columns[0]] = array ( $columns[1] => $columns[2] );
}

How Can I do the previously described?

Right now the script is stepping over the previous key getting something like this:

$array['something1'] = array ( 'hi2' => 'there2' );

I hope you can help me.

Thanks.

도움이 되었습니까?

해결책

The problem is that you are overwriting the value for the key when it already exists. You should modify to something like:

foreach ( $list as $key => $data )
{
    // extract data
    $columns    = explode ( ';' , $data );
    $outer_array_key = $columns[0];
    $key = $columns[1];
    $value = $columns[2];

    // set data
    $items[$outer_array_key][$key] = $value;
}

다른 팁

Here is how it can be done:


$list = array ( 0 => 'something;hi1;there1' , 1 => 'something;hi2;there2' );

$newlist =array();
foreach($list as $k=>$v){

    $items = explode(';',$v);
    $newlist[$items[0]][$items[1]]=$items[2];
}


echo "<pre>";
print_r($newlist);
echo "</pre>";


//output
/*
Array
(
    [something] => Array
        (
            [hi1] => there1
            [hi2] => there2
        )

)*/

?>

Change your set data with something like this :

if(!array_key_exists($columns[0], $items))
    $items[$columns[0]] = array();
$items[$columns[0]][$columns[1]] = $columns[2];
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top