Home > Mobile >  How to change indexes in array with sub arrays with subarray property value in PHP
How to change indexes in array with sub arrays with subarray property value in PHP

Time:04-13

I need help. I have an array of items like this one:

[7646] => Array
    (
        [0] => Array
            (
                [id] => 156153
                [tmplvarid] => 5
                [value] => 2
            )

        [1] => Array
            (
                [id] => 56795
                [tmplvarid] => 7
                [value] => 430
            )

        [2] => Array
            (
                [id] => 56798
                [tmplvarid] => 19
                [value] => rate_08
            )
    ),
[7647] => Array ()

And I need to change array indexes to value of property tmplvarid in sub array to transform array like this:

`[7646] => Array
    (
        [5] => Array
            (
                [id] => 156153
                [tmplvarid] => 5
                [value] => 2
            )

        [7] => Array
            (
                [id] => 56795
                [tmplvarid] => 7
                [value] => 430
            )

        [19] => Array
            (
                [id] => 56798
                [tmplvarid] => 19
                [value] => rate_08
            )
    ) 

How can I transform it in assosiative array ?

CodePudding user response:

set index value from array value using foreach loop

Code

<?PHP
  $arr = [
    "7646" => array
    (
        [
           
                "id"=> 156153,
                "tmplvarid" => 5,
                "value" => 2
            
        ],
        [
           
                "id"=> 56795,
                "tmplvarid" => 7,
                "value" => 430
            
        ],
        [
           
                "id"=> 56798,
                "tmplvarid" => 19,
                "value" => "rate_08"
            
        ]
    )
];
echo "<pre>";
print_r($arr);
$newarr= [];
foreach($arr as $key => $value)
{
    foreach($value as $key1 => $value1)
    {
        $newarr[$key][$value1['tmplvarid']] = $value1;
    }
}
print_r($newarr);
?>

Output

Array
(
    [7646] => Array(
        [5] => Array
        (
            [id] => 156153
            [tmplvarid] => 5
            [value] => 2
        )
        [7] => Array
        (
            [id] => 56795
            [tmplvarid] => 7
            [value] => 430
        )
        [19] => Array
        (
            [id] => 56798
            [tmplvarid] => 19
            [value] => rate_08
        )
    )
)
  • Related