Skip to content
Advertisement

Trimming off the not needed last x array indexes from an auto generated array

Code i’m currently using to generate the array..

<?PHP
function readCSV($csvFile){
    $file_handle = fopen($csvFile, 'r');
    fgetcsv($file_handle);
    fgetcsv($file_handle);
    fgetcsv($file_handle);  
    while (!feof($file_handle) ) {
        $line_of_text[] = fgetcsv($file_handle, 1024);
    }
    fclose($file_handle);
    return $line_of_text;
}


// Set path to CSV file
$csvFile = 'ebay.csv';

$csv = readCSV($csvFile);

$arr = [];
//$csv is your array
foreach($csv as $key => $value){
  if(!array_key_exists($value[0],$arr)){
    $arr[$value[0]] = [];
  }
  $arr[$value[0]] = array_merge($arr[$value[0]],$value);  
}
foreach ($arr as $order) :
 ?>

and it very nicely produces arrays like so..

Array
(
    [15304] => Array
        (
            [0] => 15304
            [1] => things1
            [2] => things2
        )

    [15305] => Array
        (
            [0] => 15305
            [1] => things3
            [2] => things4
        )
    [15306] => Array
        (
            [0] => 15306
            [1] => things5
            [2] => things6
        )

    [stuff] => Array
        (
            [0] => stuff
            [1] => 
            [2] => 
        )   

    [stuff2] => Array
        (
            [0] => stuff2
            [1] => foobar
            [2] => 
        )       

The arrays can have more or fewer items than my example but they always have at least 1 (sometimes 2) un-needed indexes at the end (like items [stuff] & [stuff2] in my example array.

Is there a way i can specify a value to hide the last x number of indexes?

Advertisement

Answer

Using array_pop($arr); I was able to solve my issue and when I want to remove more than 1 from the end I can repeat the code for each 1 want to chop off the end.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement