Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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;
}
share|improve this question
    
Are KEY 1, KEY 2 ... strings or are they integers? –  Oswald Jan 12 at 18:18
    
they are strings –  user3172841 Jan 12 at 18:21
    
also post print_r($csvFile) in question –  Alireza Fallah 웃 Jan 12 at 19:07
    
did you named your array to $arr ? I dont see you did –  Alireza Fallah 웃 Jan 12 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 –  user3172841 Jan 12 at 19:12
show 5 more comments

4 Answers

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.

share|improve this answer
    
That's what I call an elegant solution. Kudos. –  kuroi neko Jan 13 at 6:33
add comment

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);
share|improve this answer
add comment

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) 
      } 
}
share|improve this answer
add comment
$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);
share|improve this answer
    
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 –  user3172841 Jan 12 at 18:30
    
how do you generate it ? –  Alireza Fallah 웃 Jan 12 at 18:31
    
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); } –  user3172841 Jan 12 at 18:37
    
thats easy, look at the update –  Alireza Fallah 웃 Jan 12 at 18:42
    
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 –  user3172841 Jan 12 at 18:56
show 3 more comments

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.