2

it's my first post here, I'm a beginner and I hope you'll go easy on me. I searched for an answer, and read some semi-related questions. I've been stuck on this for a couple days and I really am very confused. Apologies if the double barrelled is a faux pas, it seemed less sensible to write this as two seperate questions. I'm new to programming and I had never heard of this website until yesterday, I hope to be a contributing part of what seems to be an awesome community.

I have an array, $newarray:

Array
(
    [2] => string1,10
    [7] => string2,15
    [10] => string3,3
    [11] => string4,7
)

I'm able to write it to a CSV file, and so far so good:

<?php
    $file = fopen("/myfile.csv","w");
    foreach ($newarray as $line)
      {
        fputcsv($file,explode(',',$line));
      }
    fclose($file);
?>

However, I'm trying to do two things.

  1. Sorting the array by reverse order of the numerical values before writing to CSV, so I would have a CSV file as so:

    string2,15
    string1,10
    string4,7
    string3,3
    
  2. Create a second file (after writing the first CSV), where the numerical values are stripped out, as so:

    string2
    string1
    string4
    string3
    

Can someone steer me in the right direction?

1
  • your array is Array ( 2 => 'string1,10', 7 => 'string2,15', 10 => 'string3,3', 11 => 'string4,7', ); ? Commented Oct 17, 2015 at 13:01

4 Answers 4

1
$arraybase = array(
    2 => 'string1,10',
    7 => 'string2,15',
    10 => 'string3,3',
    11 => 'string4,7',
);
function mapping($data){
    $array1 = array();//for first csv
    array_walk($data,function($value,$key)use(&$array1){
        $k=explode(',',$value);
        $array1[$k[1]] = $value;
    });
    krsort($array1);
    $array2 = array_map(function($value){//for second csv
        return preg_replace('/,\d+$/','',$value);
    },$array1);

    return array("csv1"=>$array1,"csv2"=>$array2);
}
$result = mapping($arraybase);
print('<pre>');print_r($result);

output:

Array
(
    [csv1] => Array
        (
            [15] => string2,15
            [10] => string1,10
            [7] => string4,7
            [3] => string3,3
        )

    [csv2] => Array
        (
            [15] => string2
            [10] => string1
            [7] => string4
            [3] => string3
        )

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

3 Comments

I tried this and it sorted by the key (11, 10, 7, 2), and not by what would be the second column in the CSV (15,10,7,3). Not sure if I'm using the correct terminology but if you try your code and compare to my question I believe you will see the difference. However, your code has helped me understand some concepts, thank you.
I've fixed all in a function.
Thank you very much miglio, I've incorporated into my code and it works perfectly.
1

Does your $newArray have to have concatinated values? If not, it's better to have them as sub-arrays:

$newArray = array (
    2 => array(
        0 => 'string1',
        1 => 10,
    ),
    7 => array(
        0 => 'string2',
        1 => 15,
    ),
    10 => array(
        0 => 'string3',
        1 => 3,
    ),
    11 => array(
        0 => 'string4',
        1 => 7,
    ),
);

Then you can sort using array_multisort:

$strings = array();
$numbers = array();
foreach ($newArray as $key => $row) {
    $strings[$key]  = $row[0];
    $numbers[$key] = $row[1];
}

array_multisort($numbers, SORT_DESC, $strings, SORT_ASC, $newArray);

When you write to the CSV:

<?php
    $file = fopen("/myfile.csv","w");
    foreach ($newArray as $line) {
        fputcsv($file, $line); // No need to explode as your data ia already in an array
    }
    fclose($file);
?>

To write to a second CSV with just the strings:

<?php
    reset($newArray); // Sets the pointer in the array back to the beginning so it can be looped over again
    $file = fopen("/myfile2.csv","w");
    foreach ($newArray as $line) {
        fputcsv($file, $line[0]);
    }
    fclose($file);
?>

Comments

0

For your first question try http://php.net/manual/en/function.rsort.php and give it at shot :)

1 Comment

This "answer" could have been a comment.
0
$a=array(/* Original array */
    2   =>  'string1,10',
    7   =>  'string2,15',
    10  =>  'string4,3',
    11  =>  'string4,7'
);      

$c=array();
foreach( $a as $index => $value ){
    list($s,$i)=explode(',', $value );
    $c[$i]=$value;
}
/* Sort in reverse order */
krsort($c);

/* The value of $c is then written to your csv */

/* callback function to get the string */
function cb(&$item,$key){
    list( $s,$i )=explode(',',$item );
    $item=$s;
}
array_walk( $c, 'cb' );

echo '<pre>',print_r($b,true),'</pre>';

2 Comments

PHP Warning: array_walk() expects parameter 1 to be array, null given in test.php on line 23. Is the output from your code as it is.
Oops, I had used the wrong variable in the array_walk function - should have been $c rather than $b

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.