Solved

php weird json result array

Posted on 2014-03-26
9
1,180 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
  • 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
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 
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 109

Accepted Solution

by:
Ray Paseur earned 500 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 109

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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

860 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