开发者

php reassign array contents [duplicate]

This question already has answers here: Transposing multidimensional arrays in PHP (12 answers) Closed 1 year ago.

any particular function or code to put this kind of array data

ori  [0] => 43.45,33,0,35 [1] => 74,10,0,22 [2] => 0,15,0,45 [3] => 0,0,0,340 [4] => 12,5,0,0 [5] => 0,0,0,0开发者_运维百科

to

new  [0] => 43.45,74,0,0,12,0 [1] => 33,10,15,0,5,0 [2] => 0,0,0,0,0,0, [3] => 35,22,45,340,0,0

As you can see, the first value from each ori are inserted into the new(0), the second value from ori are inserted into new(1) and so on


If $ori is an array of arrays, this should work:

function transpose($array) {
    array_unshift($array, null);
    return call_user_func_array('array_map', $array);
}

$newArray = transpose($ori);

Note: from Transposing multidimensional arrays in PHP

If $ori is not an array of arrays, then you'll need to convert it first (or use the example by Peter Ajtai), like this:

// Note: PHP 5.3+ only
$ori = array_map(function($el) { return explode(",", $el); }, $ori);

If you are using an older version of PHP, you should probably just use the other method!


You essentially want to transpose - basically "turn" - an array. Your array elements are strings and not sub arrays, but those strings can be turned into sub arrays with explode() before transposing. Then after transposing, we can turn the sub arrays back into strings with implode() to preserve the formatting you want.

Basically we want to go through each of your five strings of comma separated numbers one by one. We take each string of numbers and turn it into an array. To transpose we have to take each of the numbers from a string one by one and add the number to a new array. So the heart of the code is the inner foreach(). Note how each number goes into a new sub array, since $i is increased by one between each number: $new[$i++][] =$op;

foreach($ori as $one) {
    $parts=explode(',',$one);
    $i = 0;
    foreach($parts as $op) {
        $new[$i++][] =$op;
    }

}
$i = 0;
foreach($new as $one) {
    $new[$i++] = implode(',',$one);
}

// print_r for $new is:
Array
(
    [0] => 43.45,74,0,0,12,0
    [1] => 33,10,15,0,5,0
    [2] => 0,0,0,0,0,0
    [3] => 35,22,45,340,0,0
)

Working example

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜