0

I need help manipulating my two dimensional array. My array has many record sets with 2 columns of values and I'd like to manipulate the array so there is an array of many record sets with one column by converting one of my original columns as the key to the one column of values. My Array:

[0]=>
   [0]=> "48903"
   [1]=> "SDFI"
[1]=>
   [0]=> "2890"
   [1]=> "DISL"
[2] =>
   [0]=> "80890"
   [1]=> "DISL"
...plus more

Intended array:

[0]=>
   [48903]= "SDFI"
   [2890]=>"DISL"
   [80890] => "DISL"
...plus more

I've tried creating a new array with the intended keys and then unsetting the subarray but when the new array is vardumped at the end of script, it still shows that they subarray hasn't been removed. my experimental codes

$newarr=array();
foreach($arr as $val => $rename){
          $newarr[$rename[0]]= $rename;
    }

 foreach($newarr as $k => $v){
          unset($v[0]);     //does not remove/unset the extra column when newarr is var_dumped at the end of the script

  $filter = array_filter($newarr, function($k) {
   return $k == '1'; }); //or return $k !== 0; })  // other code to filter  extra column that does not seem to work.

I think I came across a similar problem from someone else but they had 3 columns for each record set and wanted to reduce the number of columns to 2 and change the extra column as a key. However, I can't seem to locate that page. If anyone could find it and post a link, that would be great.

Any help would be great.. thank you in advance.

1
  • don't suppose anyone can tell me why unsetting values or the array filter does not work? Commented Jan 30, 2015 at 20:38

2 Answers 2

0

Try this:

<?php
// the function:
function arr2kv($arr) {
    $res = array();
    foreach($arr as $v) $res[$v[0]] = $v[1];
    return $res;
}
// testing:
$n = array(
    array("48903","SDFI"),
    array("2890","DISL"),
    array("80890","DISL")
);
print_r( arr2kv($n) );
/* // result:
    Array
    (
        [48903] => SDFI
        [2890] => DISL
        [80890] => DISL
    )
*/
Sign up to request clarification or add additional context in comments.

Comments

0

Try this -

$newarr=array();
foreach($arr as $val => $rename){
      $newarr[$rename[0]]= $rename[1];
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.