2016-08-15 120 views
0

任何人都可以告訴我如何在現有的json數據中追加數組。我想這樣的代碼:在JSON上追加陣列

$response = new JsonResponse(); 
    $article = new ArticlesDevis();  
    foreach ($articlesDevis as $articleArray) { 

        $article = $articleArray; 
        $response->setData(array('image' => $article->getArticle()->getImage()->getId(),array('nom' => $article->getArticle()->getName()))); 

       } 

       return $response; 

但它只返回從$articlesDevis陣列的最後一個數據

的$ articlesDevis數組包含2門陣列(我可以得到空值的值):

object(Proxies\__CG__\ArticleBundle\Entity\Article)[1695] 
    public '__initializer__' => 
    object(Closure)[1761] 
    public '__cloner__' => 
    object(Closure)[1760] 
    public '__isInitialized__' => boolean false 
    private 'id' (ArticleBundle\Entity\Article) => int 1 
    private 'name' (ArticleBundle\Entity\Article) => null 
    private 'description' (ArticleBundle\Entity\Article) => null 
    private 'createdAt' (ArticleBundle\Entity\Article) => null 
    private 'prix' (ArticleBundle\Entity\Article) => null 
    private 'prixSolde' (ArticleBundle\Entity\Article) => null 
    private 'isSolde' (ArticleBundle\Entity\Article) => null 
    private 'percent' (ArticleBundle\Entity\Article) => null 
    private 'isVisible' (ArticleBundle\Entity\Article) => null 
    private 'enterprise' (ArticleBundle\Entity\Article) => null 
    private 'category' (ArticleBundle\Entity\Article) => null 
    private 'visit' (ArticleBundle\Entity\Article) => null 
    private 'image' (ArticleBundle\Entity\Article) => null 

object(Proxies\__CG__\ArticleBundle\Entity\Article)[1693] 
    public '__initializer__' => 
    object(Closure)[1761] 
    public '__cloner__' => 
    object(Closure)[1760] 
    public '__isInitialized__' => boolean false 
    private 'id' (ArticleBundle\Entity\Article) => int 2 
    private 'name' (ArticleBundle\Entity\Article) => null 
    private 'description' (ArticleBundle\Entity\Article) => null 
    private 'createdAt' (ArticleBundle\Entity\Article) => null 
    private 'prix' (ArticleBundle\Entity\Article) => null 
    private 'prixSolde' (ArticleBundle\Entity\Article) => null 
    private 'isSolde' (ArticleBundle\Entity\Article) => null 
    private 'percent' (ArticleBundle\Entity\Article) => null 
    private 'isVisible' (ArticleBundle\Entity\Article) => null 
    private 'enterprise' (ArticleBundle\Entity\Article) => null 
    private 'category' (ArticleBundle\Entity\Article) => null 
    private 'visit' (ArticleBundle\Entity\Article) => null 
    private 'image' (ArticleBundle\Entity\Article) => null 

它返回只有最後一個是ID = 2

{"id":2,"image":14,"0":{"nom":"Table"}} 

回答

0

讓我猜解決方案

return new JsonResponse(array_map(function ($article) { 
    return [ 
     'image' => $article->getArticle()->getImage()->getId(), 
     'nom' => $article->getArticle()->getName() 
    ]; 
}, $articlesDevis)); 
+0

謝謝你的作品 – Mostafa