1

I have a multi-dimensional array like this and I would like to create a new array out of it and add in default values. The keys of the first array are fixed (00,01,02,03) but the keys in the secondary are dynamic values

Array
(  
[00] => Array
    (
        [KEY 1] => 100
        [KEY 2] => 50
        [KEY 3] => 30
    )

[01] => Array
    (
        [KEY 1] => 40
        [KEY 2] => 100
        [KEY 4] => 200
    )

[02] => Array
    (
        [KEY 1] => 30
        [KEY 2] => 40
        [KEY 3] => 30
    )

[03] => Array
    (
        [KEY 5] => 30
    )

 )

So my question is How can I turn the above array into something like this ?

Array
(  
[00] => Array
    (
        [KEY 1] => 10
        [KEY 2] => 50
        [KEY 3] => 30
        [KEY 4] => 0
        [KEY 5] => 0
    )

[01] => Array
    (
        [KEY 1] => 40
        [KEY 2] => 100
        [KEY 3] => 0
        [KEY 4] => 200
        [KEY 5] => 0
    )

[02] => Array
    (
        [KEY 1] => 30
        [KEY 2] => 40
        [KEY 3] => 30
        [KEY 4] => 0
        [KEY 5] => 0
    )

[03] => Array
    (
       [KEY 1] => 0
       [KEY 2] => 0
       [KEY 3] => 0
       [KEY 4] => 0
       [KEY 5] => 30
    )

)

I have been struggling all day and my head is getting tired. Can some one help ?

//HERE is the code i am using

contents of the CSV file

"00","KEY 1",100
"00","KEY 2",50
"00","KEY 3",30
"01","KEY 1",40
"01","KEY 2",100
"01","KEY 4",200
"02","KEY 1",30
"02","KEY 2",40
"02","KEY 3",30
"03","KEY 5",30

Here is the code

$csvFile='export (82).csv';


$file_handle = fopen($csvFile, 'r');
while (!feof($file_handle)) {
    $line_of_text[] = fgetcsv($file_handle, 1024);
 }
 foreach ($arr as $key => $val) {
    foreach ($line_of_text as $v) {
        if (!isset($val[$v]))
            $arr[$key][$v] = 0;
    }
 }
echo"<pre>";
 print_r($arr);
 echo"</pre>";

// CODE FOR CREATING THE Multi-dimensional array

$fp = fopen($csvFile, 'r');
$master = array();
while( $line = fgetcsv( $fp ) ) {

if( !isset( $master[$line[0]] ) )
    $master[$line[0]] = array();

if( !isset( $master[$line[0]][$line[1]] ) )
    $master[$line[0]][$line[1]] = 0;

$n = filter_var($line[2], FILTER_SANITIZE_NUMBER_INT);
$master[$line[0]][$line[1]] += $n;
}
9
  • Are KEY 1, KEY 2 ... strings or are they integers? Commented Jan 12, 2014 at 18:18
  • also post print_r($csvFile) in question Commented Jan 12, 2014 at 19:07
  • did you named your array to $arr ? I dont see you did Commented Jan 12, 2014 at 19:07
  • $csvFile just opens a csv file and the contents of the file are displayed in my question; Which array should be named to $arr ? i am confused Commented Jan 12, 2014 at 19:12
  • the multi dimensional array that you said in top of your question Commented Jan 12, 2014 at 19:23

4 Answers 4

2

If your input array is $array:

// merge inner arrays to get an array that has a value for every key
$merged = call_user_func_array('array_merge', $array);

// extract the keys from that array
$keys = array_keys($merged);

// build array that has value `0` for each key
$defaults = array_fill_keys($keys, 0);

// loop over the input array, adding values for missing keys
foreach (array_keys($array) as $key) {
    $array[$key] += $defaults;
}

Note that for array_merge to give the desired result, the keys in the inner arrays need to be strings.

Sign up to request clarification or add additional context in comments.

1 Comment

That's what I call an elegant solution. Kudos.
1

I think this is what you're looking for.

$defaults = [
    'KEY 1' => 0,
    'KEY 2' => 0,
    'KEY 3' => 0,
    'KEY 4' => 0,
    'KEY 5' => 0,
];

foreach ($values as &$v) {
    $v += $defaults;
}
unset($v);

Comments

1

I think you need this:

$keys = Array("A", "B", "C", "D", "E");

$x = Array(
    Array( "A" => 10, "C" => 10),
    Array( "A" => 10, "D" => 20)
);

// Loop through $x
foreach($x as &$value){
    // Loop through the array 
    foreach($keys as $key){

        if(!in_array($key, array_keys($value))) {
            $value[ $key ] = 0;
        }
    }
}
var_dump($x);

Output:

array(2) { 
      [0]=> array(5) { 
          ["A"]=> int(10) 
          ["C"]=> int(10) 
          ["B"]=> int(0) 
          ["D"]=> int(0) 
          ["E"]=> int(0) 
      } 
      [1]=> &array(5) { 
          ["A"]=> int(10) 
          ["D"]=> int(20) 
          ["B"]=> int(0) 
          ["C"]=> int(0) 
          ["E"]=> int(0) 
      } 
}

Comments

0
$arr = array(
            00 => array
                (
                'KEY1' => 100,
                'KEY2' => 50,
                'KEY3' => 30,
            ),
            01 => array
                (
                'KEY1' => 40,
                'KEY2' => 100,
                'KEY4' => 200,
            ),
            02 => array
                (
                'KEY1' => 30,
                'KEY2' => 40,
                'KEY3' => 30,
            )
            ,
            03 => array
                (
                'KEY5' => 30,
            ),
        );
        $csv = array_unique(explode(",", str_replace("\n", ",", file_get_contents("csv.csv"))));
        foreach ($csv as $key => $value) {
            $csv[$key] = str_replace("\"","", $value);
        }

        foreach ($arr as $key => $val) {
            foreach ($csv as $v) {
                if (!isset($val[$v]))
                    $arr[$key][$v] = 0;
            }
        }
        print_r($arr);

7 Comments

thanks but the values "key1","key2",etc... are dynamic and i dont know in advance how many keys will be in that array. it may contain one, one hundred or a thousand keys
how do you generate it ?
the contents are from a csv file and this how it looks like "00","KEY 1",100 "00","KEY 2",50 "00","KEY 3",30 "01","KEY 1",40 "01","KEY 2",100 "01","KEY 4",200 "02","KEY 1",30 "02","KEY 2",40 "02","KEY 3",30 "03","KEY 5",30 and this is the code i use to put the csv contents into an array $file_handle = fopen($csvFile, 'r'); while (!feof($file_handle) ) { $line_of_text[] = fgetcsv($file_handle, 1024); }
given that the values of the array will be dynamic, do i need to declare the array the way you did in your code ? i have tried to declare $arr= array() but when i print_r the array, i get no data
no need to declare, can you post the exact code in your question so I can debug your problem?
|

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.