Access elements inside multidimensional array - php

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

Related

How to read this array in PHP

I have read other questions regarding reading arrays in PHP and implemented the suggested solutions but these do not seem to work for me...
My array looks like this:-
{
[0]=> array(6)
{ ["name"]=> string(9) "Test04Feb" [0]=> string(9) "Test04Feb"
["paymentvalue"]=> string(6) "500.00" [1]=> string(6) "500.00"
["transactiondate"]=> string(19) "2020-02-05 13:29:37" [2]=> string(19) "2020-02-05 13:29:37"
}
[1]=> array(6)
{ ["name"]=> string(9) "Test04Feb" [0]=> string(9) "Test04Feb"
["paymentvalue"]=> string(7) "1500.00" [1]=> string(7) "1500.00"
["transactiondate"]=> string(19) "1970-01-01 05:30:00" [2]=> string(19) "1970-01-01 05:30:00"
}
[2]=> array(6)
{ ["name"]=> string(9) "Test04Feb" [0]=> string(9) "Test04Feb"
["paymentvalue"]=> string(5) "90.00" [1]=> string(5) "90.00"
["transactiondate"]=> string(19) "2020-02-05 18:12:18" [2]=> string(19) "2020-02-05 18:12:18"
}
}
And none of these work for me:-
$stmt1->execute([$myname]);
$value = $stmt1->fetchAll();
...
foreach ($stmt1 as $row1) {
echo $row1[0]->name;
echo $row1['0']['transactiondate'];
echo $row1[0]['paymentvalue'];
}
Any help would be much appreciated, thank you.
Using
foreach ($stmt1 as $row1) {
$row1 is each individual record from the database. Therefore, rather than having to use [0] as in your code, you should simply be using...
echo $row1->name;
etc.
To check this for yourself, use something like print_r($row1); in the loop to see what each loop has to work with.
In your case $row1 is an array as indicated in your dump. In foreach should use $value and not $stmt. Then:
foreach ($value as $row1) {
echo $row1['name'];
}
P.S. If you want to get only associative keys, use like this:
$value = $stmt1->fetchAll(PDO::FETCH_ASSOC);
Try this if you are using foreach
foreach ($stmt1 as $row1) {
echo $row1['name'];
}
or you can use
echo $stmt1[0]['name'];
Hope this helps you

PHP Multudimensional Array foreach

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

PHP how to get value from array with foreach

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'];
}

Cut array by sub array key value

I got this array
array(5) {
[0]=>
array(5) {
["id"]=>
int(1411667077)
["nachricht"]=>
string(13) "iiiiiiiiiiiii"
["user"]=>
string(15) "334607943355808"
["datum"]=>
string(16) "25.09.2014 19:44"
["deleted"]=>
string(0) ""
}
[1]=>
array(5) {
["id"]=>
int(1411701734)
["nachricht"]=>
string(2) "dd"
["user"]=>
string(15) "334607943355808"
["datum"]=>
string(16) "26.09.2014 05:22"
["deleted"]=>
string(0) ""
}
[2]=>
array(5) {
["id"]=>
int(1411701737)
["nachricht"]=>
string(6) "swfsfs"
["user"]=>
string(15) "334607943355808"
["datum"]=>
string(16) "26.09.2014 05:22"
["deleted"]=>
string(0) ""
}
[3]=>
array(5) {
["id"]=>
int(1411701739)
["nachricht"]=>
string(7) "egwegeg"
["user"]=>
string(15) "334607943355808"
["datum"]=>
string(16) "26.09.2014 05:22"
["deleted"]=>
string(0) ""
}
[4]=>
array(5) {
["id"]=>
int(1411742201)
["nachricht"]=>
string(3) "sss"
["user"]=>
string(15) "334607943355808"
["datum"]=>
string(16) "26.09.2014 16:36"
["deleted"]=>
string(0) ""
}
}
I want to cut the where the id is 1411701737 so I tryed:
foreach($array as $arr => $sub_arr)
{
if $sub_arr['id'] == 1411701737
{
break;
}
}
I know I need to create a whole new array in the foreach, but isn't there maybe a build in function?
$arr_new = array(); //Define a new array
foreach($arr_old as $a) { //Loop through the old one
if($a['id'] === 1411701737) break; //If the value of id matches, leave the foreach loop
$arr_new[] = $a; //Else, copy this array to the new array
}
print_r($arr_new); //Print the new array
$new = array();
foreach($array as $k) {
if($k['id'] == 1411701737) break;
array_push($new, $k);
}
var_dump($new);
The answer by Mooseman is likely a faster way to do this since it does not rely on a PHP function call to place the array into the new array. However unless you are doing this on a set of arrays that is in the 100k+ it really won't matter.

Converting Json String into PHP array then using php array

Im new to json & php and I'm having some issues with json into php string
My json string looks like this
{"status":"OK","cards":
[{"id":100001,"name":"batman","image":11111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T11:37:07Z"},
{"id":100002,"name":"superman","image":111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T12:30:09Z"},
{"id":100003,"name":"catwoman","image":1111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T12:39:42Z"},
{"id":100004,"name":"bane","image":1111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-09-08T12:56:04Z"}
]}
So Far i have created my string
$json_raw = '{"status":"OK","cards": [{"id":100001,"name": .....
Decoded the json
$arr = json_decode($json_raw, TRUE);
I var_dump($arr);
then it returns
array(2) { ["status"]=> string(2) "OK" ["cards"]=> array(4) { [0]=> array(8) { ["id"]=> int(100001) ["name"]=> string(6) "batman" ["image"]=> int(11111) ["size"]=> int(75) ["region_id"]=> int(1) ["locked"]=> bool(false) ["status"]=> string(6) "active" ["created_at"]=> string(20) "2013-08-15T11:37:07Z" } [1]=> array(8) { ["id"]=> int(100002) ["name"]=> string(8) "superman" ["image"]=> int(111111) ["size"]=> int(75) ["region_id"]=> int(1) ["locked"]=> bool(false) ["status"]=> string(6) "active" ["created_at"]=> string(20) "2013-08-15T12:30:09Z" } [2]=> array(8) { ["id"]=> int(100003) ["name"]=> string(8) "catwoman" ["image"]=> int(1111111) ["size"]=> int(75) ["region_id"]=> int(1) ["locked"]=> bool(false) ["status"]=> string(6) "active" ["created_at"]=> string(20) "2013-08-15T12:39:42Z" } [3]=> array(8) { ["id"]=> int(100004) ["name"]=> string(4) "bane" ["image"]=> int(1111111) ["size"]=> int(75) ["region_id"]=> int(1) ["locked"]=> bool(false) ["status"]=> string(6) "active" ["created_at"]=> string(20) "2013-09-08T12:56:04Z" } } }
Now all I want to do is be able to use this data
e.g if name = batman then
I know this is a stupid question but I am struggling :(
Thank in Advance
json_decode() with TRUE as second parameter gives you an associative array. You need to access the correct index to do what you want.
To list the complete associative array with nice formatting, you can do:
echo '<pre>', print_r($arr), '</pre>';
Now, to access the name in your array:
$man = $arr['cards'][0]['name'];
To check if it's Batman (yay!):
if( isset($man) && $man == 'batman' ) {
# code ...
}
For getting the name of all similar names:
$man = $json['cards']['0']['name'];
for ($i=0; $i < count($json['cards']); $i++) {
echo $json['cards'][$i]['name']."\n";
}
See it live!
when you got the array
$arr = json_decode($json_raw, TRUE);
then check if cards key exist
if(array_key_exists('cards', $arr)){
foreach($arr['cards'] as $key=>$val){
echo $key; ///name, id..
echo $val; /// batman,...
if($key == 'name' && $val =='batman'){
//-------do your stuff
}
}
}
Try with:
$cards = $arr['cards'];
foreach($cards as $card) {
if($card['name'] == 'batman') echo 'Hello batman!';
}
EDIT:
Ok, so this worked for me using code above, try it yourself if you want:
<?php
$json_raw = '{"status":"OK","cards":
[{"id":100001,"name":"batman","image":11111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T11:37:07Z"},
{"id":100002,"name":"superman","image":111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T12:30:09Z"},
{"id":100003,"name":"catwoman","image":1111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T12:39:42Z"},
{"id":100004,"name":"bane","image":1111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-09-08T12:56:04Z"}
]}';
$arr = json_decode($json_raw, TRUE);
$cards = $arr['cards'];
foreach($cards as $card) {
if($card['name'] == 'batman') echo 'Hello batman!';
}
?>

Categories