Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

php weird json result array

Posted on 2014-03-26
9
Medium Priority
?
1,270 Views
Last Modified: 2014-03-26
I'm returning a json result out of a pdo query like this:
json_encode($query->fetchAll(PDO::FETCH_ASSOC));

And when i receive i do it like this:
$array	= json_decode($output,true);
print_r($array);

Open in new window

and gives me this:
Array
(
    [0] => Array
        (
            [packstamp] => pmarketing
        )

    [1] => Array
        (
            [packstamp] => peventos
        )

    [2] => Array
        (
            [packstamp] => psystem
        )

    [3] => Array
        (
            [packstamp] => ploja
        )

    [4] => Array
        (
            [packstamp] => pproject
        )

)

Open in new window

And the json string is this:
[{"packstamp":"pmarketing"},{"packstamp":"peventos"},{"packstamp":"psystem"},{"packstamp":"ploja"},{"packstamp":"pproject"}]

Open in new window

i can't parse this right....
I try to get the value of each packstamp like this:
foreach($array as $row) {
	echo trim($row['packstamp']);
}

Open in new window

And the result is always the same, the value of the first column "pmarketing,pmarketing,etc..." instead of "pmarketing,peventos,etc..."

I thought the foreach would the same as i do with the parse of the pdo array result, but i guess not...

Can someone help me?

Thx in advanced,
Miguel
0
Comment
Question by:justaphase
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 2
9 Comments
 
LVL 1

Author Comment

by:justaphase
ID: 39956968
correction... i was doing a return during my foreach in my production code..
it gives all results, the only problem is that repeats the results 5 times...
like this
pmarketing
peventos
psystem
ploja
pproject
pmarketing
peventos
psystem
ploja
pproject
pmarketing
peventos
psystem
ploja
pproject
pmarketing
peventos
psystem
ploja
pproject
pmarketing
peventos
psystem
ploja
pproject

Open in new window

0
 
LVL 9

Expert Comment

by:rfportilla
ID: 39957013
Try this:

foreach ($array as $row) {
	print $row['packstamp'] . "\n";	
}

Open in new window

0
 
LVL 9

Expert Comment

by:rfportilla
ID: 39957015
Nevermind, ignore last comment.  Not paying attention.  Will reread post.
0
Free Backup Tool for VMware and Hyper-V

Restore full virtual machine or individual guest files from 19 common file systems directly from the backup file. Schedule VM backups with PowerShell scripts. Set desired time, lean back and let the script to notify you via email upon completion.  

 
LVL 9

Expert Comment

by:rfportilla
ID: 39957030
I am confused how you got that output without "\n".  

Regarding repeating results, did you put a foreach inside a foreach?  Can you give a little more code?  

I'm testing with this and it works fine for me.  

<?php
$array = json_decode('[{"packstamp":"pmarketing"},{"packstamp":"peventos"},{"packstamp":"psystem"},{"packstamp":"ploja"},{"packstamp":"pproject"}]', true);

foreach($array as $row) {
	echo trim($row['packstamp']);
}

Open in new window

0
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 2000 total points
ID: 39957111
This is a compound statement:

json_encode($query->fetchAll(PDO::FETCH_ASSOC));

Open in new window

Compound statements are PHP AntiPractice #9.  Don't write code like that - it's a sure signal that a programmer is not very experienced, and it's very hard to debug.   Instead, write one line of code on each line of the program script.  You probably want something like this so you can visualize the data that is returned from the PDOStatement object.

while ($row = $query->fetchAll(PDO::FETCH_OBJ))
{
    // ROW BY ROW PROCESSING IS DONE HERE
    foreach ($row as $key => $obj)
    {
        echo "$key: ";
        print_r($obj);
        echo PHP_EOL;
    }
}

Open in new window

Once you see the return data you will immediately have a better idea how to use it with JSON_Encode().   If you can make those changes and show us the output of the foreach() loop, then we can move right on to getting the JSON string right.
0
 
LVL 1

Author Comment

by:justaphase
ID: 39957451
Ray,

Sorry for not telling the all story.
I don't use the "PDO::FETCH_ASSOC", in fact i don't use it at all.
I do like this:
$pdo->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$query->execute();
and
$query->fetchAll();
And as always worked fine for me.
But since with json_encode was giving me this kind of array, i tried with "PDO::FETCH_ASSOC" (i saw it in stackoverflow). I'm only using this with json results.

I'm gonna try as you say.
0
 
LVL 1

Author Closing Comment

by:justaphase
ID: 39957462
Amazing! Works.
Like a boos Ray.

Thx
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 39957509
Great!  Glad we got it pointed in the right direction :-)
0
 
LVL 1

Author Comment

by:justaphase
ID: 39957688
Like boss lol... not boos
0

Featured Post

Enterprise Mobility and BYOD For Dummies

Like “For Dummies” books, you can read this in whatever order you choose and learn about mobility and BYOD; and how to put a competitive mobile infrastructure in place. Developed for SMBs and large enterprises alike, you will find helpful use cases, planning, and implementation.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Containers like Docker and Rocket are getting more popular every day. In my conversations with customers, they consistently ask what containers are and how they can use them in their environment. If you’re as curious as most people, read on. . .
Backups and Disaster RecoveryIn this post, we’ll look at strategies for backups and disaster recovery.
In this video, Percona Solution Engineer Dimitri Vanoverbeke discusses why you want to use at least three nodes in a database cluster. To discuss how Percona Consulting can help with your design and architecture needs for your database and infras…
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…

721 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question