2017-06-15 65 views
0
$nesAry=array(); 
$nesAry["name"]="abc"; 
$nesAry["email"]="[email protected]"; 

$nesAry1=array(); 
$nesAry1["name"]="abc1"; 
$nesAry1["email"]="[email protected]"; 

$nesAry2=array(); 
$nesAry2["name"]="abc2"; 
$nesAry2["email"]="[email protected]"; 


$responseAry = array(); 
$responseAry[0]=$nesAry; 
$responseAry[1]=$nesAry1; 
$responseAry[2]=$nesAry2; 


echo json_encode($responseAry); // here output like this => [{"name":"abc","email":"[email protected]"},{"name":"abc1","email":"[email protected]"},{"name":"abc2","email":"[email protected]"}] 

unset($responseAry[1]); 

echo "------------removed 1--------"; 


echo json_encode($responseAry); // but here output like this => {"0":{"name":"abc","email":"[email protected]"},"2":{"name":"abc2","email":"[email protected]"}} 

我想出來把篩選移除元素\ n [{「名」之後:「ABC」,「電子郵件」:「[email protected]」 },{ 「名」: 「ABC2」, 「電子郵件」: 「[email protected]」}]刪除陣列的給定鍵的元素在PHP

請幫我

+0

([使用PHP json_encode當刪除數組索引參考] https://stackoverflow.com/q最終陣列/ 20372982/6521116) –

回答

1

嘗試取消設置項後重新生成陣列:

$nesAry=array(); 
$nesAry["name"]="abc"; 
$nesAry["email"]="[email protected]"; 

$nesAry1=array(); 
$nesAry1["name"]="abc1"; 
$nesAry1["email"]="[email protected]"; 

$nesAry2=array(); 
$nesAry2["name"]="abc2"; 
$nesAry2["email"]="[email protected]"; 


$responseAry = array(); 
$responseAry[0]=$nesAry; 
$responseAry[1]=$nesAry1; 
$responseAry[2]=$nesAry2; 


echo json_encode($responseAry); // __here output like this => [{"name":"abc","email":"[email protected]"},{"name":"abc1","email":"[email protected]"},{"name":"abc2"}]__ 

unset($responseAry[1]); 

$responseAry = array_values($responseAry); //regenerate array(reindexing) 

echo "------------removed 1--------"; 


echo json_encode($responseAry); //[{"name":"abc","email":"[email protected]"},{"name":"abc2","email":"[email protected]"}] 

編輯:

至於其他選項,您可以使用array_splice方法http://php.net/manual/en/function.array-splice.php

$nesAry=array(); 
$nesAry["name"]="abc"; 
$nesAry["email"]="[email protected]"; 

$nesAry1=array(); 
$nesAry1["name"]="abc1"; 
$nesAry1["email"]="[email protected]"; 

$nesAry2=array(); 
$nesAry2["name"]="abc2"; 
$nesAry2["email"]="[email protected]"; 


$responseAry = array(); 
$responseAry[0]=$nesAry; 
$responseAry[1]=$nesAry1; 
$responseAry[2]=$nesAry2; 


echo json_encode($responseAry); // __here output like this => [{"name":"abc","email":"[email protected]"},{"name":"abc1","email":"[email protected]"},{"name":"abc2"}]__ 

array_splice($responseAry,1,1); 
echo "------------removed 1--------"; 


echo json_encode($responseAry); 
+0

還有其他選擇嗎? –

+0

@publicksoftss查看我編輯的答案 –

+0

非常感謝你的回答 –

0

你的數組時先轉換爲JSON是一種所謂的「聯想」的數組,並json_encode然後將其出口到你看到對象在第一個回聲中。

在您取消設置後,數組將更改爲「數字」數組,並且json_encode將使用數組鍵將數組導出。

Php它自己不關心數組是如何使用的,但json_encode的確如此。

您可以使用

echo json_encode(array_values($responseAry));

不改要導出

+0

它對我很有用,非常感謝你 –