7 Replies - 715 Views - Last Post: 13 July 2013 - 08:19 AM Rate Topic: -----

#1 oneshot2shots  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 13-July 13

undefined offset/JSON array irregularities

Posted 13 July 2013 - 06:58 AM

I am trying to build a metasearch engine, and have the following code for one of the engines.

<?php

if(isset($_GET['response']) && $_GET['response'] != "")
	{
 
		echo "<br />Your Search Result Array:<br /><br />";
 
	$url =  'http://www.faroo.com/api?start=1&length=10&l=en&src=web&i=false&f=json&key=kgYsYaXONbiOCY1LoAs41bVcRVs_&'.'q='.str_replace(' ', '%20', $_GET['response']);
 
	// sendRequest
	// note how referer is set manually
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_REFERER, 'http://www.google.com');
	$body = curl_exec($ch);
	curl_close($ch);
 



	
	// now, process the JSON string
	


$json = json_decode($body,true); 

 
 

//var_dump ($json);


for($i=0; $i < 4 ;$i++)
{
	
	foreach ($json['results'] as $URL)
	
{
echo $URL [$i]['url']."<br /";


}



	foreach ($json['results'] as $TITLE)

	
{
echo  $TITLE  [$i]['title']." <br /";


 

}

foreach ($json['results'] as $content)

	{
echo  $content [$i]['content']."<p>";
	}



 

 


	}



	


	
	}
	
?>




This gives me an undefined offset error (numerous times as its in a loop). I have the same code working for the google search engine which has a similar JSON array. A var_dump $json of the above produces




array
  'results' => 
    array
      0 => 
        array
          'title' => string 'Third Girl Dies From Asiana Airlines Crash Injuries' (length=51)
          'kwic' => string 'ABC News  Third Girl Dies From Asiana Airlines Crash Injuries  ABC News  The death toll from the Asiana Airlines crash has risen to three after ...' (length=147)
          'content' => string '' (length=0)
          'url' => string 'http://abcnews.go.com/US/girl-dead-asiana-airlines-crash-injuries/story?id%3D19653989' (length=85)
          'iurl' => string 'http://t3.gstatic.com/images?q=tbn:ANd9GcTeceoMLPpM44qIVYT10OlalnxuqJg-R_UrzY3DmHGL8poGLSeeHZT5rnZKcQOnGnevOkmlkoL5' (length=115)
          'domain' => string 'abcnews.go.com' (length=14)
          'author' => string '' (length=0)
          'news' => boolean true
          'votes' => string '30' (length=2)
          'date' => float 1373718533000
          'related' => 
            array
              ...
      1 => 
        array
          'title' => string 'After divisive debate, Texas Senate OKs restrictive abortion measure - CNN.com' (length=78)
          'kwic' => string 'A bill that places new restrictions on abortion passed the Texas Senate on Friday after days of debate that galvanized activists nationwide. ...' (length=144)
          'content' => string '' (length=0)
          'url' => string 'http://edition.cnn.com/2013/07/13/politics/texas-abortion-measure/' (length=66)
          'iurl' => string 'http://i2.cdn.turner.com/cnn/dam/assets/130711161630-exp-texas-abortion-controversy-00002001-story-top.jpg' (length=106)
          'domain' => string 'edition.cnn.com' (length=15)
          'author' => string '' (length=0)
          'news' => boolean true
          'votes' => string '1' (length=1)
          'date' => float 1373712819000
          'related' => 
            array
              ...
      2 => 
        array
          'title' => string 'Napolitano Stepping Down as Homeland Security Chief' (length=51)
          'kwic' => string 'Politico  Napolitano Stepping Down as Homeland Security Chief  New York Times  WASHINGTON  Janet Napolitano, the secretary of homeland security, ...' (length=151)
          'content' => string '' (length=0)
          'url' => string 'http://www.nytimes.com/2013/07/13/us/politics/napolitano-stepping-down.html?pagewanted%3Dall' (length=92)
          'iurl' => string 'http://t2.gstatic.com/images?q=tbn:ANd9GcRyhUnSIqp0iDAZDDoAHS8bJrl09b1PFZuicr6YcbFn2BO3JN058q5labnq5K3hiWDRqwtCw4k' (length=114)
          'domain' => string 'www.nytimes.com' (length=15)
          'author' => string '' (length=0)
          'news' => boolean true
          'votes' => string '30' (length=2)
          'date' => float 1373676379000
          'related' => 
            array
              ...
      3 => 
        array
          'title' => string 'Jurors in Zimmerman murder trial resume deliberations in Florida' (length=64)
          'kwic' => string 'SANFORD, Florida (Reuters) - Jurors in the second-degree murder trial of George Zimmerman ended their first day of deliberations without reaching ...' (length=149)
          'content' => string '' (length=0)
          'url' => string 'http://news.yahoo.com/jurors-zimmerman-murder-trial-resume-deliberations-florida-132356488.html' (length=95)
          'iurl' => string 'http://media.zenfs.com/en_us/News/Reuters/2013-07-13T132356Z_1_CBRE96C118C00_RTROPTP_2_USA-FLORIDA-SHOOTING.JPG' (length=111)
          'domain' => string 'news.yahoo.com' (length=14)
          'author' => string '' (length=0)
          'news' => boolean true
          'votes' => string '25' (length=2)
          'date' => float 1373721836000
          'related' => 
            array
              ...
      4 => 



The
 foreach  ($json['results'] as $content)

	{
echo  $content [$i]['content']."<p>";
	}


gives an undefined offset error. However
foreach  ($json] as $content)

	{
echo  $content ['results'] [$i]['content']."<p>";
	}
[/code]

gives an error index 'results' not defined, which does not make any sense to me. Can anyone point me in the right direction, I have been rearranging the foreach's and array order for 2 days now and this is as far as i've gotten.

TTTIA

Is This A Good Question/Topic? 0
  • +

Replies To: undefined offset/JSON array irregularities

#2 CTphpnwb  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3001
  • View blog
  • Posts: 10,393
  • Joined: 08-August 08

Re: undefined offset/JSON array irregularities

Posted 13 July 2013 - 07:22 AM

Get one thing working at a time, starting with this:
for($i=0; $i < 4 ;$i++)
{
	
	foreach ($json['results'] as $URL)
	
{
echo $URL [$i]['url']."<br /";


}


It's missing a closing brace and the indenting is horrific.
It also looks to me like the loops are in the wrong order.
foreach ($json['results'] as $URL)
{
	for($i=0; $i < 4;$i++)
	{
		echo $URL[$i]['url']."<br /";
	}
}

Don't enter the other loops until these two do what you expect. Then, and only then, add another loop and test. Don't proceed without a successful test.

This post has been edited by CTphpnwb: 13 July 2013 - 07:23 AM

Was This Post Helpful? 1
  • +
  • -

#3 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3522
  • View blog
  • Posts: 12,030
  • Joined: 12-December 12

Re: undefined offset/JSON array irregularities

Posted 13 July 2013 - 07:27 AM

echo  $content [$i]['content']."<p>";

You need to break the habit of putting an extra space between the array-name (object-name) and the element (attribute) reference.

I've only had a quick look but I don't think you need [$i], you are already looping through the elements of 'results'. I might be wrong about the $i though.

echo  $content['content']."<p>";

The content is an empty string though - test with one of the other values.

This post has been edited by andrewsw: 13 July 2013 - 07:30 AM

Was This Post Helpful? 1
  • +
  • -

#4 oneshot2shots  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 13-July 13

Re: undefined offset/JSON array irregularities

Posted 13 July 2013 - 07:39 AM

View Postandrewsw, on 13 July 2013 - 07:27 AM, said:

echo  $content [$i]['content']."<p>";

You need to break the habit of putting an extra space between the array-name (object-name) and the element (attribute) reference.

I've only had a quick look but I don't think you need [$i], you are already looping through the elements of 'results'. I might be wrong about the $i though.

echo  $content['content']."<p>";

The content is an empty string though - test with one of the other values.


without the $i it produces a single result, I'm trying to get it to display the url, then title, then content, then loop back and do the same a number of times but it for some reason only outputs on eurl. Messy as the code is it worked for google and that's what i can't get my head around.
Was This Post Helpful? 0
  • +
  • -

#5 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3522
  • View blog
  • Posts: 12,030
  • Joined: 12-December 12

Re: undefined offset/JSON array irregularities

Posted 13 July 2013 - 07:51 AM

Did you read CTphpnwb 's post as well?

Personally, I would break into down into steps. I would first attempt to echo a single value:

echo $json['results'][0]['title'];    // or whatever works!

Once I've successfully displayed a value I would then know the correct way to reference the items, and then put it into an appropriate looping structure.

This post has been edited by andrewsw: 13 July 2013 - 07:52 AM

Was This Post Helpful? 1
  • +
  • -

#6 oneshot2shots  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 13-July 13

Re: undefined offset/JSON array irregularities

Posted 13 July 2013 - 08:04 AM

View Postandrewsw, on 13 July 2013 - 07:51 AM, said:

Did you read CTphpnwb 's post as well?

Personally, I would break into down into steps. I would first attempt to echo a single value:

echo $json['results'][0]['title'];    // or whatever works!

Once I've successfully displayed a value I would then know the correct way to reference the items, and then put it into an appropriate looping structure.


Well
 for($i=0; $i < 4;$i++)

	{
	 	foreach ($json['results'] as $URL)  
	    {
	        echo $URL['url']."<br /"  ;
			
	    }
	
	}
produces a single url. Without the for loop it produces a single url. If i put 10 echo statements inside the foreach loop it produces a single url. And i don't understand why the above works but
 for($i=0; $i < 4;$i++)

	{
	 	foreach ($json as $URL)  
	    {
	        echo $URL['results']['url']."<br /"  ;
			
	    }
doesent, giving an invalid argument in the foreach loop. This is what's bugging me, and that's why I put in the $i to try and get it to output more urls. I'm beginning to think it might be something different like faroo only giving out one url per query (and hope that isin't the case as it is ridiculously low). Anyway thanks for the help guys I'll post up the code when I figure it out.
Was This Post Helpful? 0
  • +
  • -

#7 CTphpnwb  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3001
  • View blog
  • Posts: 10,393
  • Joined: 08-August 08

Re: undefined offset/JSON array irregularities

Posted 13 July 2013 - 08:17 AM

Are you sure it's one url? Could it be that "<br /" is not a line break? Try "<br>".
Was This Post Helpful? 0
  • +
  • -

#8 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3522
  • View blog
  • Posts: 12,030
  • Joined: 12-December 12

Re: undefined offset/JSON array irregularities

Posted 13 July 2013 - 08:19 AM

"<br /" should be "<br />" or "<br/>", or can be "<br>" with HTML5.

$json is a single object, which happens to contain other objects. Well, in fact, it only contains the single object 'results', so

foreach ($json as $URL)

only performs a single iteration.

I would try

$results = $json['results'];

and then ignore $json from then on.

However, I may be wrong as I haven't tested this.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1