threeedv
threeedv

Reputation: 59

How to modify PHP array keys

I have some basic data coming from a csv upload, the table is formatted like so:

Cost 1 Cost 2 Cost 3
5 12 5
1 13 9
9 0 1

The data saves to the database and using array_chunk I have an array that looks like this (I will need to loop through these later)

array(
  [0] => Array
      (
          [Cost 1] => 5
      )
  [1] => Array
      (
          [Cost 2] => 12
      )
  [2] => Array
      (
          [Cost 3] => 3
      )
   )

I want to modify the array to read the keys as values instead, so the final array would look like this with the column title saving in every instance:

array(
  [0] => Array
      (
          [cost] => Cost 1
          [demand] => 5
      )
  [1] => Array
      (
          [cost] => Cost 2
          [demand] => 12
      )
  [2] => Array
      (
          [cost] => Cost 3
          [demand] => 3
      )
   )

I know I can use array_keys and array_values to target each, but can't quite get my head around how I'd use that to create the above.

Upvotes: 1

Views: 168

Answers (2)

Beshambher Chaukhwan
Beshambher Chaukhwan

Reputation: 1448

$newCostArray=[];
foreach($costArray as $index => $carr) {
  $newCostArray[$index]=[];
  foreach($carr as $key => $val) {
     echo "$key = $val<br>";
     $newCostArray[$index]['cost']=$key;
     $newCostArray[$index]['demand']=$val;
  }
}

Upvotes: 0

azibom
azibom

Reputation: 1944

This script work for you
I first iterate the array with foreach and then in each element use the array_keys and array_values for give the keys and values and because that is just one row in the element I use the [0]

<?php

$array = [
    [
        "Cost 1" => 5
    ],
    [
        "Cost 2" => 12
    ],
    [
        "Cost 3" => 3
    ],
];

$formattedArray = [];
foreach($array as $element) {
    $formattedArray[] = [
        "cost" => array_keys($element)[0],
        "demand" => array_values($element)[0],
    ];
}

print_r($formattedArray);

output

Array
(
    [0] => Array
        (
            [cost] => Cost 1
            [demand] => 5
        )

    [1] => Array
        (
            [cost] => Cost 2
            [demand] => 12
        )

    [2] => Array
        (
            [cost] => Cost 3
            [demand] => 3
        )
)

Upvotes: 1

Related Questions