HI我試圖轉換JavaScript代碼php.below是JavaScript代碼轉換javascript代碼塊到PHP
<script>
var prefs = '["w",32,"r","s",2,"w",65,"w",26,"w",45,"w",24,"w",40,"s",2]';
var si = "hellocode";
var sig = (si + "").split("");
function swap(arr, b) {
l3 = arr[0];
l4 = arr[b % arr.length];
arr[0] = l4;
arr[b] = l3;
return arr
}
var cmd = JSON.parse(prefs||'["r","r"]');
cmd.forEach(function (c, i) {
if (typeof c !== "string") {
return;
}
switch (c) {
case "r":
sig = sig.reverse();
break;
case "s":
sig = sig.slice(cmd[i+1]);
break;
case "w":
sig = swap(sig, cmd[i+1]);
break;
}
});
</script>
我有什麼在PHP
<?php
$prefs = '["w",32,"r","s",2,"w",65,"w",26,"w",45,"w",24,"w",40,"s",2]';
$si = "hellocode";
$arr = str_split($si);
$sig = implode(',', $arr);
function swap($arr, $b) {
$cool = explode(",",$arr);
$l3 = $cool[0];
$l4 = $cool[$b % length($cool)];
$cool[0] = $l4;
$cool[$b] =$l3;
return $cool;
}
// $cool = json_decode($prefs||'["r","r"]');
//now i am struck with converting $prefs to array
$i=0;
foreach($cool as $c)
{
// how to get type of string here ?
// And what does slice function do ?
}
我到目前爲止已經試過在第二部分發生?請參閱評論和一些專家在js到php ..請指點我:)
http://us3.php.net/is_string檢查變量是否爲字符串;無論如何,array.slice返回包含兩個參數之間的數組的元素。 http://www.w3schools.com/jsref/jsref_slice_array.asp(抱歉w3school)。如果省略第二個參數,它將從數組的開始到結束。也就是說,如果從1切片數組,它將返回從1到數組結尾(到array.length)的所有元素。 array.slice等效於PHP實際上是array_slice函數:http://us1.php.net/array_slice – briosheje
嘿謝謝:)如何將$ prefs轉換爲數組? –
好吧,我不是json中的神,但是因爲它是一個json字符串,所以你應該使用json_decode來解決問題! http://php.net/manual/en/function.json-decode.php – briosheje