1

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.

2 Answers 2

1

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
        )
)
Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what I needed, thank you so much for your help.
0
$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;
  }
}

2 Comments

Rather than adding the link to your answer as a comment, add a line of text "As suggested here we can do something like". It improves the readability of your question and can improve the answers performance (votes).
I created that link though 😂 but thanks alot I'll keep that in mind @Oliver 🥺

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.