Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

php - How to transpose array elements?

I have an array $categories in php as follows.

Array
(
    [item_name] => Array
        (
            [0] => I-Phone
            [1] => samsung
            [2] => nokia
            [3] => htc
        )

    [item_price] => Array
        (
            [0] => 30.00
            [1] => 20
            [2] => 10
            [3] => 15
        )
)

And I want to transpose its element as,

Array
(
    [0] => Array
        (
            [item_name] => I-Phone
            [item_price] => 30.00
        )

    [1] => Array
        (
            [item_name] => samsung
            [item_price] => 20
        )
    [2] => Array
        (
            [item_name] => nokia
            [item_price] => 10
        )

    [2] => Array
        (
            [item_name] => htc
            [item_price] => 15
        )
)

I've tried using foreach loop but not working.

$count=0;
foreach ($categories as $key=> $category)
{
        $categories[$count] = $category[$key];
        $categories[$count] = $category[$key];
        $count++;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here's an approach:

$categories = array(
    'item_name' => array('I-Phone', 'samsung', 'nokia','htc'),
    'item_price' => array('30.00', '20', '10', '15')
);

$out = array();
foreach($categories as $key => $a){
    foreach($a as $k => $v){
        $out[$k][$key] = $v;
    }
}
echo '<pre>';
print_r($out);
echo '</pre>';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...