简体   繁体   English

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

[英]skip first value for variable inside of foreach loop php

I have the following function on my site which grabs all the values from $vid_pix , and echos each them or any associated variables in a foreach loop. 我的网站上有以下函数,该函数从$vid_pix所有值,并在foreach循环中回显每个值或任何关联的变量。

Which works fine, however I have a variable - $Pt that also gets echoed out as well. 效果很好,但是我有一个变量- $Pt ,它也会被回显

Right now though what I am trying to do is - skip the first value in $Pt . 现在虽然我想做的是-跳过$Pt的第一个值。 Also set a static value for the last instance since everything is being moved up 1, leaving the last with no value. 还应为最后一个实例设置静态值,因为一切都将向上移动1,而最后一个实例则没有任何值。

I've tried array_splice and unset , but it's not skipping the first $Pt value. 我已经尝试过array_spliceunset ,但它没有跳过第一个$Pt值。

So if I had - 所以如果我有-

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

I would need - 我会需要 -

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

(x = I would have to assign a static value for the last variable.) (x =我必须为最后一个变量分配一个静态值。)

My function (stripped down for simplicity) 我的功能(为简单起见而减少)

$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';
    }
 }

To put things into better context, here's the full code for the specific function I'm trying to achieve this within -- 为了更好地说明问题,这是我正在尝试实现的特定功能的完整代码-

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

UPDATE 更新

var_dump results - var_dump结果-

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

The following link contains the original code which saves the $Pt variable -- here 以下链接包含保存$Pt变量的原始代码- 此处

Based on OP's comments , $Pt is an array of array. 根据OP的注释$Pt是一个数组数组。 So we simply use array_shift to remove the first value (second level array). 因此,我们仅使用array_shift删除第一个值(第二级数组)。 And, append an array of static value to the end: 并且,将静态值数组附加到末尾:

$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);
}

UPDATE #1 更新#1

Try using array_shift() like this: 尝试像这样使用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
}

UPDATE #2 更新#2

If there's actually just one photo_time meta for each image/attachment (the attachment IDs are in the $vid_pix array), then this should work: 如果每个图像/附件实际上只有一个 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

UPDATE #3 更新#3

Add the above ( $Pt2 ) code above /before this foreach , then add the $i => , and change the $Pt as you can see below: 将以上( $Pt2在此之前) 上面的代码/ foreach ,然后添加$i =>并更改$Pt ,你可以看到如下:

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

Why not to do it in the simplest way? 为什么不以最简单的方式做到这一点?

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

Please correct me if I understood it wrong. 如果我理解错了,请纠正我。

you could simply proceed like this: 您可以这样简单地进行:

$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);

output : 输出:

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

How about ? 怎么样 ?

$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
  )
);

Check it in live here : https://repl.it/repls/PerfectUpsetAnalysts 在此处实时检查: 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++;
 }

use this type of counter for skipping value.... 使用这种类型的计数器跳过值。

As you already know you are getting photo_time of each vid_pix and in your question I see you need to get photo_time of next vid_pix for current vid_pix and ignore the first photo_time which is 5 in provided example and the last vid_pix (put something static instead) 正如你已经知道你所得到photo_time每个vid_pix在你的问题,我看,你需要得到photo_time未来的vid_pix当前vid_pix而忽略了第一photo_time这是5提供的示例和最后vid_pix (放东西,而不是静态)

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

I would need - 我会需要 -

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

so I think its simple (I use vip_pix index as key, you can use whatever) 所以我认为它很简单(我使用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

You need to shift the array outside the loop since your $Pt array has single value. 您需要将数组移到循环外,因为$Pt数组具有单个值。 Try the code given below. 尝试下面给出的代码。

$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);

Hope this helps. 希望这可以帮助。

How about passing the results of get_post_meta($vP, 'photo_time', false); 如何传递get_post_meta($vP, 'photo_time', false); into a function that shifts the values and adds the static value to the end? 转换为可移动值并将静态值添加到末尾的函数?

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;
}

So essentially you could just wrap your existing function like so... 因此,基本上,您可以像这样包装您现有的功能...

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

... and this would leave the last value in the array as null while shifting all of the original values up. ...,这会将数组中的最后一个值保留为空,同时将所有原始值上移。

If you wanted to specify the final value (eg as 5 ) then you could do... 如果要指定最终值(例如5 ),则可以...

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

You can use array_slice to remove one set of value from the array and use array_merge to merge it with the "x". 您可以使用array_slice从数组中删除一组值,并使用array_merge将其与“ x”合并。

Then you just combine the keys and "new" values. 然后,您只需组合键和“新”值即可。

$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);

This outputs: 输出:

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 https://3v4l.org/l7NBa

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM