Results 1 to 2 of 2

Thread: array_splice vs array_unshift

  1. #1
    Join Date
    Jan 2008
    Posts
    441
    Thanks
    67
    Thanked 4 Times in 4 Posts

    Default array_splice vs array_unshift

    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
    Code:
    $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++;
    }
    Last edited by ggalan; 09-19-2011 at 03:22 PM.

  2. #2
    Join Date
    Jan 2008
    Posts
    441
    Thanks
    67
    Thanked 4 Times in 4 Posts

    Default

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

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •