+2 votes
7.5k views
in Programming by Expert (3.8k points)

I have a function PHP getData which is returning some data on the basis of ID which we are passing in the function i.e   getData($ID);

Now printing data like :

$print = getData(323);

print_r($print );

 

Array ( [0] => Array ( [ID] => 323 [product] => samsung ))

 

When I am printing results on the basis of key so result is coming blank.


Please See and suggest : print_r($print[‘product’]);

3 Answers

+1 vote
by (990 points)

Hi Jatin as you can see your result ,here are 2 different arrays

 

  1. Array having 0 index Array [0].

  2. Array having Index as ID Array [ID]=>323

 

So you have to print like this :

 

    

print_r($print[0] [‘product’]);

Now it would print 0 index of first array with index ID(323).

So you would get your results on the basis of specific array key.hope you got my point.

+1 vote
by Expert (5.1k points)
reshown by

Firstly, As i make out. You want to get the product info like it's name and ID.

1- if you want to fetch the product name it can be done by two method.

First - example:

$print = getData(323);

 

     by using array key so what you have to do just.

   print_r($print [0][product]);

output: samsung.

 

Second example  -

if you don't want to use the array key then just use any one loop. like see example below

foreach ($print as $print ):

echo $print [product];

endforeach;

output - samsung.

 

try this! may be you will get the point

 

 

 

0 votes
by

print_r is used to quickly output the content of an array abd shouldn't really be used to print a single value. Use print or echo instead. 
Your function getData() returns an array of arrays, and in your example it is an array containing just 1 array. It is that array that contains the keys you are trying to reach. 
Since it is an array in an array, you also need to define the key of the outer array which is 0. So to find the value from the 'product' key, you need to address $print[0]['product'] 

print($print[0]['product']);

Not a Member yet?

Ask to Folks Login

My Account

Your feedback is highly appreciated