Using PHP and MySQL, I have generated an array called $response.
A var_dump of $response can be seen here.
array(2) {
["OperationRequest"]=>
array(4) {
["HTTPHeaders"]=>
array(1) {
[0]=>
array(1) {
["#attributes"]=>
array(2) {
["Name"]=>
string(9) "UserAgent"
["Value"]=>
string(14) "ApaiIO [2.1.0]"
}
}
}
["RequestId"]=>
string(36) "f53f381e-efb3-4fef-8e39-4f732b4b463e"
["Arguments"]=>
array(1) {
["Argument"]=>
array(11) {
[0]=>
array(1) {
["#attributes"]=>
array(2) {
["Name"]=>
string(14) "AWSAccessKeyId"
["Value"]=>
string(20) "KEY"
}
}
[1]=>
array(1) {
["#attributes"]=>
array(2) {
["Name"]=>
string(12) "AssociateTag"
["Value"]=>
string(11) "TAG"
}
}
[2]=>
array(1) {
["#attributes"]=>
array(2) {
["Name"]=>
string(6) "IdType"
["Value"]=>
string(4) "ISBN"
}
}
[3]=>
array(1) {
["#attributes"]=>
array(2) {
["Name"]=>
string(6) "ItemId"
["Value"]=>
string(38) "0751538310,9780141382067,9781305341141"
}
}
[4]=>
array(1) {
["#attributes"]=>
array(2) {
["Name"]=>
string(9) "Operation"
["Value"]=>
string(10) "ItemLookup"
}
}.......so on
A json_encode of the array can be seen here (as requested in a comment).
I'd like to select the Title from these two items. From what I can see this is located at;
Items > Item > ItemAttributes > Author
So, using a foreach loop I have tried the following;
foreach ($response as $item) {
echo $item['Items']['Item']['ItemAttributes']['Title']; // line 2
}
However this returns the following error;
Message: Undefined index: Items. Line Number: 2
Where am I going wrong and what must I change in my code in order to achieve the desired result?
Also, any advice on how to 'read' multidimensional arrays would be greatly appreciated.
Thanks
Try this one, it will help you out. You were are iterating on the wrong key that's why you were not getting desired output.
Try this code snippet herefrom json provide by OP in question
foreach($array["Items"]["Item"] as $key => $value)
{
print_r($value["ItemAttributes"]["Title"]);
echo PHP_EOL;
}
Output:
Panic
Panic
Captain Flinn and the Pirate Dinosaurs: Missing Treasure! (Captain Flinn)
For getting unique titles:
foreach(json_decode($json,true)["Items"]["Item"] as $key => $value)
{
$result[]=$value["ItemAttributes"]["Title"];
echo PHP_EOL;
}
print_r(array_unique($result));
#Also, any advice on how to 'read' multidimensional arrays would be greatly appreciated.
Post your encoded json string to
http://json.parser.online.fr
"+" and "-" button at the right panel should help you read it easily.
//Check Items is not empty
if( !isset($response["Items"]["Item"]) || empty($response["Items"]["Item"]) )
throw New Exception("Empty Item");
foreach($response["Items"]["Item"] as $item){
$title = $item['ItemAttributes']['Title']
}
You should debug as:
foreach ($response as $key => $item) {
if(isset($item['Items'])){ //Check Items index defined
echo $item['Items']['Item']['ItemAttributes']['Title'];
}else{
var_dump($key);
}
}
Related
I've the following array$_SESSION['survey_ans'][]=$records;
and will get the result withvar_dump($_SESSION['survey_ans']);
array(6) {
[0]=> array(1) {
[1]=> string(5) "vpoor"
}
[1]=> array(1) {
[10]=> string(4) "poor"
}
[2]=> array(1) {
[6]=> string(7) "average"
}
[3]=> array(1) {
[11]=> string(4) "good"
}
[4]=> array(1) {
[12]=> string(5) "vgood"
}
[5]=> array(1) {
[13]=> string(4) "good"
}
}
But when I run this
foreach($_SESSION['survey_ans'] as $key=>$value) {
echo $key."-".$value."<br />";
}
I will get the error "Notice : Array to string conversion in ". So how do I get the result as following?
1, vpoor
10, poor
6, average
11, good
12, vgood
13, good
The elements of $_SESSION['survey_ans'] are arrays, so you need to iterate through the values in each array to get your desired output. Try this:
foreach($_SESSION['survey_ans'] as $result) {
foreach ($result as $key => $value) {
echo $key."-".$value."<br />";
}
}
Output:
1-vpoor
10-poor
6-average
11-good
12-vgood
13-good
Demo on 3v4l.org
I'm trying to gather a group of term_id's output in a foreach and create an array from them. I then want to update the taxonomy with the values in the array however the array is being created as multi-level. My code is as follows:
$updateTax = array();
foreach ($featuresArray as $key => $value) {
if ($key = 'en_value') {
$termResult = get_term_by('name', $value['en_value'], $taxonomy);
$term = $termResult->term_id;
$updateTax[] = array($term);
}
}
...which then gives this output:
var_dump($updateTax);
array(29) {
[0]=> array(1) {
[0]=> int(111) } [1]=> array(1) {
[0]=> int(116) } [2]=> array(1) {
[0]=> int(124) } [3]=> array(1) {
...
[0]=> int(408) } [25]=> array(1) {
[0]=> int(447) } [26]=> array(1) {
[0]=> int(520) } [27]=> array(1) {
[0]=> int(593) } [28]=> array(1) {
[0]=> int(628) }
}
...but I was expecting the following:
array(29) {
[0]=> int(111) }
[1]=> int(116) }
[2]=> int(124) }
[3]=> int(125) }
...
Bit puzzled so could do with some guidance please. Many thanks.
Replace the following line, where you are creating an individual array for each $term:
$updateTax[] = array($term);
With this:
$updateTax[] = $term;
I have array $result
array(2) {
["Smiley TV"]=>
array(2) {
["Speed"]=>
array(2) {
[0]=>
string(4) "9510"
[1]=>
string(5) "33775"
}
["Turbo"]=>
array(2) {
[0]=>
string(4) "2427"
[1]=>
string(5) "19696"
}
}
["Victory Media"]=>
array(1) {
["Speed"]=>
array(2) {
[0]=>
string(4) "4144"
[1]=>
string(5) "80445"
}
}
}
How with foreach i can get values. For example in the "Smyley TV" how i can result "Speed".
Also please write how i can get all data one by one. Thanks
You can fetch this way
foreach ($arrays as $array) {
echo $array['smyley TV'];
}
I return this array of objects from an API call like so. Note that $result is an array of arrays with $result[data] holding todo list objects and result[success] holding status of API call:
array(9) { [0]=> object(stdClass)#3 (5) { ["todo_id"]=> string(10) "1480430478" ["title"]=> string(13) "Check Printer" ["description"]=> string(8)
"Room 233" ["due_date"]=> string(10) "11/29/2016" ["is_done"]=> string(4) "true" } [1]=> object(stdClass)#4 (5) { ["todo_id"]=> string(10) "148043046" ["title"]=> string(18) "Doctor Appointment" ["description"]=> string(7)
"#4pm. " ["due_date"]=> string(10) "11/30/2016" ["is_done"]=> string(4) "true" }
etc..
I sort the array with usort fine and then I want to resort on the "is_done" field and put them at bottom of todo list in date order. The php to do this is :
//Sort by is_done
foreach($result[data] as $arrayElement ) {
foreach($arrayElement as $valueKey => $value) {
if(($valueKey == 'is_done') && ($value == 'true')){
$temp = $arrayElement;
//delete this particular object from the $array
unset($result[data][$arrayElement]);
array_push($result[data], $temp);
}
}
}
The problem I am having is my completed items are now at the end of the array but they are also still in their original position. The unset is not working. I have tried all variations on referencing the $result[data] item to no avail. This is probably something simple but I need some help if possible. Googling and checking this site shows no examples of unset in this type of situation. Thanks in advance.
Update:
after applying colburton's solution the API is now returning this data structure:
object(stdClass)#3 (6) { ["2"]=> object(stdClass)#4 (5) { ["todo_id"]=> int(1480698596) ["title"]=> string(7) "Test #4" ["description"]=> string(4) "test" ["due_date"]=> string(10) "12/02/2016" ["is_done"]=> string(5) "false" } ["3"]=> object(stdClass)#5 (5) { ["todo_id"]=> string(10) "1480617975" ["title"]=> string(13) "Check Printer" ["description"]=> string(4)
"Test" ["due_date"]=> string(10) "12/06/2016" ["is_done"]=> string(5) "false" } ["5"]=> object(stdClass)#6 (5) { ["todo_id"]=> int(1481136023) ["title"]=> string(9) "Todo item" ["description"]=> string(7) "test123" ["due_date"]=> string(10) "01/19/2017" ["is_done"]=> string(5) "false" } etc...
At the end of the call i do a
//json_decode the result
$result = #json_decode($result);
//check if we're able to json_decode the result correctly
if ($result == false || isset($result->success) == false) {
throw new Exception('Request was not correct');
}
//if there was an error in the request, throw an exception
if ($result->success == false) {
throw new Exception($result['errormsg']);
}
//if everything went great, return the data
return $result->data;
}
and then in main program I reference $result as
$result = $todo_items[0];
And that is where fatal error occurs now.
Update II:
Wanted to add that you then need to reindex the array
$result['data'] = array_values($result['data']);
I read here that this is a bug in json_decode. Thanks for the help....
Please use quotes around your array indices. This unsets what you want:
foreach ($result['data'] as $idx => $arrayElement) {
foreach ($arrayElement as $valueKey => $value) {
if (($valueKey == 'is_done') && ($value == 'true')) {
$temp = $arrayElement;
//delete this particular object from the $array
array_push($result['data'], $temp);
unset($result['data'][$idx]);
}
}
}
I have this multidimensional array in PHP:
array(4) {
["took"]=> int(2)
["timed_out"]=> bool(false)
["_shards"]=> array(3) {
["total"]=> int(5)
["successful"]=> int(5)
["failed"]=> int(0)
}
["hits"]=> array(3) {
["total"]=> int(3)
["max_score"]=> float(2.3578677)
["hits"]=> array(1) {
[0]=> array(5) {
["_index"]=> string(13) "telephonebook"
["_type"]=> string(6) "person"
["_id"]=> string(22) "M5vJJZasTGG2L_RbCQZcKA"
["_score"]=> float(2.3578677)
["_source"]=> array(8) {
["Mob"]=> string(19) "XXX"
["Title"]=> string(13) "Analyst"
["Department"]=> string(8) "Analysis"
["Country"]=> string(6) "Sweden"
["Tlf"]=> string(0) ""
["Name"]=> string(16) "XXX"
["Email"]=> string(29) "XX#retro.com"
["thumbnailPhoto"]=> string(0) ""
}
}
}
}
}
The array has several "hits" inside "hits" and I want to loop trough and print out the stuff inside "_source". I have tried a few different approaches but I cant figure out any way to do this. Please help me.
foreach ($array['hits']['hits'][0]['_source'] as $key => $value) {
//do stuff
}
Try this
foreach ($arr['hits']['hits'] as $val)
{
echo $val['_source']['Mob'];
}
like this
I think this may handle it for you. Replace $the_array_you_provided with your "main" array variable (you've not specified it in the post).
$hits = $the_array_you_provided['hits']['hits'];
foreach ($hits as $hit) {
echo $hit['_source']['Title'];
//print everything in the array
//print_r($hit['_source']);
}
Any help feel free to ask.
Try this:
foreach ($array['hits']['hits'] as $hit) {
foreach ($hit['_source'] as $source) {
echo $source, '<br>';
}
}