跳过 foreach 循环内变量的第一个值 php

skip first value for variable inside of foreach loop php

我的网站上有以下功能,它从 $vid_pixechos 中获取所有值或 foreach 中的任何相关变量环形。

效果很好,但是我有一个变量 - $Pt 也得到 echoed

虽然我现在想做的是 - 跳过 $Pt 中的第一个值。还为最后一个实例设置一个静态值,因为所有内容都向上移动 1,最后一个没有值。

我试过 array_spliceunset,但它没有跳过第一个 $Pt 值。

所以如果我有 -

[vp 1]->[5]
[vp 2]->[10]
[vp 3]->[15]
[vp 4]->[20]

我需要 -

[vp 1]->[10]
[vp 2]->[15]
[vp 3]->[20]
[vp 4]->[x]

(x = 我必须为最后一个变量分配一个静态值。)

我的功能(为简单起见被精简)

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

foreach ($vid_pix as $vP) {
    $Pt = get_post_meta($vP, 'photo_time', false);
    array_splice($Pt, 0, 1);
    //unset($Pt[0]);
    $Pt = get_post_meta($vP, 'photo_time', true);
    echo $Pt;

    if (last -> $Pt) { // something like this for the last value
        $Pt = '5';
    }
 }

为了更好地说明问题,这里是我试图在其中实现的特定功能的完整代码 --

/*
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;
        } );

        foreach ($vid_pix as $vP) {
$filename = basename( get_attached_file( $vP ));
$Pt = get_post_meta($vP, 'photo_time', true);
$Por = get_post_meta($vP, 'photo_order', true);

$static_value=25;
$array=$Pt;

reset($array);//reset the internal pointer
while(false!==($key=key($array))&&null!==key($array)){//check for current key validity
    $next=next($array);//get the next value and move the pointer
    $array[$key]=$next&&isset($array[$key])?$next:$static_value;//assign the next value to the current key  if valid or the static value if false 
}

var_dump($Por);
var_dump($array);

// try to determine the pic of the placeholder image

if ($vP === end($vid_pix))
        $last_img = $thepath.'/'.$filename;


if ($vstyle === 'Custom') { // if custom timing is chosen

$slide_dur = "\r\nduration ".$Pt;

$filename = basename( get_attached_file( $vP ));
$line .= "file '".$thepath."/".$filename."'".$slide_dur."\r\n";


} else { // if custom timing is NOT chosen

$filename = basename( get_attached_file( $vP ));
$line .= "file '".$thepath."/".$filename."'".$slide_dur."\r\n";

}

$total_items = count($vid_pix);

if ($total_items > 1) { // if total items is more than one

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

$isitone = "";
$solopic = "";


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

} else { // if total items is less than one

$isitone = "true";
$solopic = "-loop 1 -probesize 10M -i ".$thepath."/".$filename;

}
}

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

更新

var_dump 结果 -

string(1) "7"
string(1) "2"
string(1) "6"
string(1) "9"

下面的link包含保存$Pt变量的原始代码——here

, $Pt is an array of array. So we simply use array_shift的基础上去掉第一个值(二级数组)。并且,在末尾附加一个静态值数组:

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

foreach ($vid_pix as $vP) {
    $Pt = get_post_meta($vP, 'photo_time', false);

    // $Pt is an array of array
    // remove the first key (first array)
    $first_key = array_shift($Pt);

    // Add the static value to end of the array. eg: '5'
    $static_value = '5'; // define static value
    $Pt[] = array($static_value);

    // print them out
    var_dump($Pt);
}

为什么不以最简单的方式来做呢?

$keys = array_keys($myHashArray);
$values = array_values($myHashArray);
array_shift($keys);
array_shift($values);
$result = array_combine($keys, $values);

理解有误请指正

您可以这样简单地进行:

$static_value=25;
$array=['vp 1'=>5,'vp 2'=>10,'vp 3'=>15,'vp 4'=>20];

reset($array);//reset the internal pointer
while(false!==($key=key($array))&&null!==key($array)){//check for current key validity
    $next=next($array);//get the next value and move the pointer
    $array[$key]=$next&&isset($array[$key])?$next:$static_value;//assign the next value to the current key  if valid or the static value if false 
}


var_dump($array);

输出:

array(4) {
  ["vp 1"]=>
  int(10)
  ["vp 2"]=>
  int(15)
  ["vp 3"]=>
  int(20)
  ["vp 4"]=>
  int(25)
}

怎么样?

$new_array = array_combine( // to make an array from $keys / values
  array_keys($old_array), // use the old same keys
  array_merge( // the array containing your new values
    array_splice($old_array, 1), // remove the first element
    [$static_value] // add the static value
  )
);

现场查看:https://repl.it/repls/PerfectUpsetAnalysts

$vid_pix = get_post_meta($v_Id, 'vid_pix', false);
$i = 0;
foreach ($vid_pix as $vP) {
   if($i ==0){
continue;
}
    $Pt = get_post_meta($vP, 'photo_time', false);
    array_splice($Pt, 0, 1);
    //unset($Pt[0]);
    $Pt = get_post_meta($vP, 'photo_time', true);
    echo $Pt;

    if (last -> $Pt) { // something like this for the last value
        $Pt = '5';
    }
$i++;
 }

使用这种类型的计数器来跳过值....

正如您已经知道的那样,每个 vid_pix 都得到了 photo_time,在您的问题中,我看到您需要得到下一个 vid_pixphoto_time 当前 vid_pix 并忽略第一个 photo_time,在提供的示例中为 5,最后一个 vid_pix(改为静态)

[vp 1]->[5]
[vp 2]->[10]
...

我需要 -

[vp 1]->[10]
[vp 2]->[15]
...

所以我觉得很简单(我使用vip_pix index作为键,你可以使用任何东西)

$pt_result = [];
for ($i = 0; $i < count($vid_pix) - 1; ++$i) {
    $pt_result[$vid_pix[$i]] = get_post_meta($vid_pix[$i+1], 'photo_time', true);
}
$pt_result[$vid_pix[$i]] = 25; //set last one statically

您需要将数组移出循环,因为您的 $Pt 数组只有一个值。试试下面给出的代码。

$newPt = array(); // initialize new array
$vid_pix = get_post_meta($v_Id, 'vid_pix', false);

foreach ($vid_pix as $vP) {
    $Pt = get_post_meta($vP, 'photo_time', false);

    // assign to new array
    $newPt[] = $Pt;
}

// remove first value
array_shift( $newPt );

// add static value to end of the array
$static = '5';
$newPt[] = array( $static );

// print updated array
var_dump($newPt);

希望对您有所帮助。

如何将 get_post_meta($vP, 'photo_time', false); 的结果传递到一个函数中,该函数会移动值并将静态值添加到末尾?

function shiftPt($input, $end = null) {
    $output = [];
    $prevKey = null;
    foreach ($input as $key => $value) {
        if ($lastKey) $output[$lastKey] = $value;
        $lastKey = $key;
    }
    $output[$key] = $end;
    return $output;
}

所以基本上你可以像这样包装你现有的函数...

$pT = shiftPt(get_post_meta($vP, 'photo_time', false));

... 这会将数组中的最后一个值保留为 null,同时向上移动所有原始值。

如果您想指定最终值(例如 5),那么您可以...

$pT = shiftPt(get_post_meta($vP, 'photo_time', false), 5);

更新#1

尝试像这样使用 array_shift()

foreach ($vid_pix as $vP) {
    $Pt2 = get_post_meta($vP, 'photo_time', false);
    $Pt = array_shift( $Pt2 ); // get first value
    $Pt2[] = 'static value';
    var_dump( $Pt, $Pt2 ); // test
}

更新#2

如果每个 image/attachment 实际上只有 一个 photo_time 元(附件 ID 在 $vid_pix 数组中),那么这个应该工作:

$Pt2 = [];
$n = count( $vid_pix );
for ( $i = 0, $j = 1; $i < $n; $i++, $j++ ) {
    $Pt2[] = ( $n === $j ) ? 'static value' :
        get_post_meta( $vid_pix[ $j ], 'photo_time', true );
}
echo implode( ', ', $Pt2 ); // test

更新#3

在这个foreach之前添加上面的($Pt2)代码above/,然后添加$i =>,并更改$Pt 如下所示:

foreach ($vid_pix as $i => $vP) {
  $filename = basename( get_attached_file( $vP ));
  $Pt = $Pt2[ $i ];
  ...
}

您可以使用 array_slice 从数组中删除一组值,然后使用 array_merge 将其与 "x".

合并

然后您只需组合键和 "new" 值。

$arr = [
'vp 1'=>[5],
'vp 2'=>[10],
'vp 3'=>[15],
'vp 4'=>[20]];

$keys = array_keys($arr);
$values = array_merge(array_slice($arr, 1), ["x"]);

$new = array_combine($keys, $values);
var_dump($new);

这输出:

array(4) {
  ["vp 1"]=>
  array(1) {
    [0]=>
    int(10)
  }
  ["vp 2"]=>
  array(1) {
    [0]=>
    int(15)
  }
  ["vp 3"]=>
  array(1) {
    [0]=>
    int(20)
  }
  ["vp 4"]=>
  string(1) "x"
}

https://3v4l.org/l7NBa