subtract array values from each other creating new

2019-08-21 07:43发布

问题:

On my site I have the following code, which grabs values from a form and creates a text file with a list of my image paths and duration times. --

/*
This is for looping through the uploaded pictures
and sorting them and creating a text file.
*/

$vid_pix = get_post_meta($v_Id, 'vid_pix', false);

$data = "ffconcat version 1.0";
$line = '';

        usort( $vid_pix, function( $a, $b ){
            $aPor = (int) get_post_meta( $a, 'photo_order', true );
            $bPor = (int) get_post_meta( $b, 'photo_order', true );

            if ( $aPor === $bPor ) {
                return 0;
            }

            return ( $aPor < $bPor ) ? -1 : 1;
        } );

// this function removes the first value and shifts the array back so that key 1 = value 2, etc.

$Pt2 = [];
$n = count( $vid_pix );
for ( $i = 0, $j = 1; $i < $n; $i++, $j++ ) {
    $Pt2[] = ( $n === $j ) ? '6' :
        get_post_meta( $vid_pix[ $j ], 'photo_time', true );
}

        foreach ($vid_pix as $i => $vP ) {

$filename = basename( get_attached_file( $vP ));
$Por = get_post_meta($vP, 'photo_order', true);
$Pt = $Pt2[ $i ];

// try to determine the pic of the placeholder image
if ($vP === end($vid_pix))
        $last_img = $thepath.'/'.$filename;

// THIS IS THE LINE THAT OUTPUTS THE NUMBERS I NEED
$slide_dur = "\r\nduration ".$Pt;

$line .= "file '".$thepath."/".$filename."'".$slide_dur."\r\n"; 

// LAST LINE OF CONCAT TEXT FILE
$lastline = "file '".$last_img."'\r\nduration 2\r\nfile '".$last_img."'";

// PUT TOGETHER ALL THE LINES FOR THE TEXT FILE
$txtc = $data."\r\n".$line.$lastline;

// SAVE THE TEXT FILE
file_put_contents($thepath.'/paths.txt', $txtc);

Then the output using 5, 10, 13, 16, 6 looks like this --

ffconcat version 1.0
file 'home1.png'
duration 5
file 'home2.png'
duration 10
file 'home3.png'
duration 13
file 'home4.png'
duration 16
file 'home5.png'
duration 6 // last number in regards to my question
file 'home5.png'
duration 2
file 'home5.png'

What I need to do though is subtract each value with the value before it, and making a new value for that key. The values will always be dynamic.

So first key - 5 would stay 5, it would stay the same.

The second key - 10, will become 5 because 10-5.

Then the third key - 13, will become 3 because 10-13.

The fourth key - 16, will become 3 because 16-13.

Im not sure if I explained that right so if any more details are needed let me know.

回答1:

Shouldn't be too hard; I'm not sure where the confusion is. If you want to subtract, just subtract? So instead of outputting $Pt, just output $Pt - $Pt2[$i-1]. You'll probably want to add a condition to just use $Pt if $i === 0.