skip to Main Content

From mycsv.csv
$data[7] has these:

4294967296/4294967296  
4294967296  
8589934592/8589934592  

I want to calculate and put GB, so they become like this:

4GB/4GB  
4GB  
8GB/8GB

What I did:

<?php

$a = str_ireplace("/"," ",$data[7]);  
echo (floor($a/1000000000))."GB";

But it gives error for the ones that have /:

Warning: A non-numeric value encountered in… on line 45 4GB

Help Please… Thank you


Sorry, I think I describe it wrong.
So, I have a csv file with many data in it.

while (! feof($CSVvar)) {
        $data = fgetcsv($CSVvar, 1000, ",");
        if (! empty($data)) {
            ?>
            <tr>
                <td><?php echo $data[0]; ?></td>
                <td><?php echo $data[7]; ?></td></tr>

will give among others:

$data[7]

4294967296/4294967296

then another

$data[7]

4294967296

and so on..

2

Answers


  1. $data[7] = [
    '4294967296/4294967296',
    '4294967296',
    '8589934592/8589934592',
    ];
    foreach($data[7] as $data){
        $data_spilt = explode('/',$data);
        $strGb = [] ;
        foreach($data_spilt as $gb){
            $strGb[] = (floor($gb/1000000000))."GB";
        }
        echo implode('/',$strGb)."<br>";
    }
    

    Hope this will help you

    Login or Signup to reply.
  2. You can’t floor a string like 4294967296 4294967296 after you do the str_ireplace. You will need a bit of looping for this but I have tried to make it as short as possible for you keeping it readable(hopefully).

    So, split the string based on new lines so you would get each string in a separate array index.

    Now, for each string of the form x/y or x itself, we split the string based on /. Now, we divide each number in the array by 1e9 to convert bytes to Giga bytes and implode them back with a GB suffix attached to it.

    Finally, we collect these results in a new array and implode them back using a new line character.

    <?php
    
    $result = [];
    
    foreach(explode("n", $data[7]) as $str){
        $result[] = implode("GB/", array_map(fn($v) => floor($v / 1e9), explode("/", $str))). 'GB';
    }
    
    echo implode("n", $result);
    

    Live Demo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search