Jnewbie
Jnewbie

Reputation: 163

How can i select a single value in array php?

Since arrays in PHP are more like hash maps im strugling to get a single value instead of the whole array

My json object:

[{
"title": "Hello world1",
"placement": "world",
"time": "today",
"tags": "Hello world im stucked"
 },{
"title": "Hello world2",
"placement": "world2",
"time": "today2",
"tags": "Hello2 world2 im2 stucked2"
 }]

My getTags function:

    function getTags($string){
       $tags[] = explode(" " , $string);
       return $tags;
    }

My code is iterating a json object($obj), getting the "tags" of each iteration, splitting them in an array called "$tags" with a function getTags(//string to split) and iterating them again to get the value of each iteration.

 //Iterate json
 for ($i = 0 ; $i < sizeof($obj) ; $i++){

    //split the tags string to array (" ")
    $tags[] = getTags($obj[$i]->tags);

    //Iterate tags array
    for($z = 0; $z < sizeof($tags); $z++) {

       //get the value of the array
       var_dump($tags[$z]).die;
     }
}

The result will be:

array(1) { [0]=> array(4) { [0]=> string(5) "Hello" [1]=> string(5) "world" [2]=> string(2) "im" [3]=> string(7) "stucked" } }

Instead of what i was expecting:

String(5) "Hello"

Upvotes: 0

Views: 77

Answers (2)

roberto06
roberto06

Reputation: 3864

Just remove the [] after $tags in both the declaration and the use of your getTags function :

$json = '[{
"title": "Hello world1",
"placement": "world",
"time": "today",
"tags": "Hello world im stucked"
 },{
"title": "Hello world2",
"placement": "world2",
"time": "today2",
"tags": "Hello2 world2 im2 stucked2"
 }]';

function getTags($string){
   $tags = explode(" " , $string);
   return $tags;
}

$obj = json_decode($json);

//Iterate json
for ($i = 0 ; $i < sizeof($obj) ; $i++){

    //split the tags string to array (" ")
    $tags = getTags$obj[$i]->tags);

    //Iterate tags array
    for($z = 0; $z < sizeof($tags); $z++) {

    //get the value of the array
    var_dump($tags[$z]).die;
 }

Upvotes: 2

Manjeet Barnala
Manjeet Barnala

Reputation: 2995

use php explode function to split string into array like below:

$data = '[{
"title": "Hello world1",
"placement": "world",
"time": "today",
"tags": "Hello world im stucked"
 },{
"title": "Hello world2",
"placement": "world2",
"time": "today2",
"tags": "Hello2 world2 im2 stucked2"
 }]';

$dataArray = json_decode($data,true); ///return json object as associative array. 
for ($i = 0 ; $i < sizeof($dataArray) ; $i++)
{
    $tags = explode(' ',$dataArray[$i]['tags']);//split the string into array.
    for ($z = 0 ; $z < sizeof($tags) ; $z++) //loop throug tags array
    {
        echo $tags[$z];
        die; ///remove this for further excecution.
    }
} 

Will give you :

Hello

Upvotes: 1

Related Questions