Log in

View Full Version : Resolved array_splice vs array_unshift



ggalan
09-19-2011, 12:06 AM
i am trying to reorganize my json file using array_splice.
this is part of my code, using array_unshift works great, but i dont want the item placed on the end,
rather i would like to replace the original spot using splice but i get weird out put


$dataFile = 'data/data.json';
$dataTxt = file_get_contents($dataFile);
$dataList = json_decode($dataTxt,true);
$arrImg = array();
$stack = array();

$j = 0;
foreach($dataList['data'] as $indexItems){
array_push($stack, $indexItems['index']);
array_push($arrImg, $indexItems['img']);
$j++;
}

$k = 0;
foreach($dataList['data'] as $indexItems){
if (isset($_POST['reload'.$k])) {

$pos = $dataList['data'][$k]['index'];
$newTxt = $_POST["text$k"];
$newImg = $dataList['data'][$k]['img'];

$dataArr = array('index'=>$pos,'text'=>$newTxt,'img'=>$newImg);

//array_unshift($dataList['data'], $dataArr);// this works
array_splice($dataList['data'], -$pos, 0, $dataArr);//<< error
unset($dataList['data'][$k+1]);


$dataTxt = json_encode($dataList);
}
$k++;
}

ggalan
09-19-2011, 03:22 PM
fixed:


array_splice($dataList['data'], -$pos, 0, array($dataArr))