Jnewbie Jnewbie - 3 months ago 14
JSON Question

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"

Answer

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;
 }
Comments