Tejas Khutale
Tejas Khutale

Reputation: 84

I want to use array function to convert array

I have array like below.I want to convert this array but I want to use array function.is there any array function to convert below array

[name] => Array
            (
                [0] => Cash Crops
                [7] => Cereal Crops
                [12] => Vegetables
                [25] => Leafy Vegetables
                [28] => Vine Vegetables
            )

into this array

        [0] => Array
            (
                [name] => Cash crops
            )

        [1] => Array
            (
                [name] => Pulse crops
            )

        [2] => Array
            (
                [name] => Oil seed crops
            )

        [3] => Array
            (
                [name] => Cereal Crops
            )

Upvotes: 0

Views: 85

Answers (4)

Amarnasan
Amarnasan

Reputation: 15569

This oneliner works with any 'name':

$tal = array_map(function($x) use($array)  {return array( array_keys($array)[0] => $x);}, $array[array_keys($array)[0]]);

Upvotes: 0

bIgBoY
bIgBoY

Reputation: 417

The best way you can do this using a native php function is by using array_map()

<?php
function twod($n)
{
    $res = array('name' => $n);
    return($res);
}

$a['name'] = array(1, 2, 3, 4, 5);
$new_array = array_map("twod", $a['name']);
print_r($new_array);
?>

Please be sure to let the community know why you want something in a particular way instead of just saying "I can write logic to convert it but I want array function"

Upvotes: 2

Alex Andrei
Alex Andrei

Reputation: 7283

Using array_walk applied to the inner name array

$a = array(
    'name' => array(
        'Cash Crops','Cereal Crops','Vegetables','Leafy Vegetables','Vine Vegetables'
    )
);

$result = array();

array_walk($a['name'],
    function($value,$index) use (&$result){
        $result[] = array(
            'name' => $value
        );
});

print_r($result);

Will output

Array
(
    [0] => Array
        (
            [name] => Cash Crops
        )

    [1] => Array
        (
            [name] => Cereal Crops
        )

    [2] => Array
        (
            [name] => Vegetables
        )

    [3] => Array
        (
            [name] => Leafy Vegetables
        )

    [4] => Array
        (
            [name] => Vine Vegetables
        )

)

Upvotes: 4

Jesse
Jesse

Reputation: 76

$oldarray = array()//your array with old data;
$newarray = convertArray($oldarray);

function convertArray($old){
    $new = array();
    foreach($old as $index=>$value)
    {
        $new[]['name'] = $value;
    }
    return $new;
}

This would convert it to your array.

Upvotes: 1

Related Questions