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
Related
I have an array that I exploded by Regex, here is a part of the array named $data;
array(6) {
[0]=>
array(1) {
[0]=>
string(77) "Achnanthes brevipes C.Agardh, Syst. Alg.: 1 (1824). / Küçük sucıncığı."
}
[1]=>
array(1) {
[0]=>
string(10) "Achnanthes"
}
[2]=>
array(1) {
[0]=>
string(8) "brevipes"
}
[3]=>
array(1) {
[0]=>
string(8) "C.Agardh"
}
[4]=>
array(1) {
[0]=>
string(21) "Syst. Alg.: 1 (1824)."
}
[5]=>
array(1) {
[0]=>
string(22) "Küçük sucıncığı"
}
}
array(6) {
[0]=>
array(1) {
[0]=>
string(89) "Achnanthes cocconeiformis Mann, U.S. Nat. Mus., Bull. 6: 182 (1925). / Top sucıncığı."
}
[1]=>
array(1) {
[0]=>
string(10) "Achnanthes"
}
[2]=>
array(1) {
[0]=>
string(14) "cocconeiformis"
}
[3]=>
array(1) {
[0]=>
string(4) "Mann"
}
[4]=>
array(1) {
[0]=>
string(36) "U.S. Nat. Mus., Bull. 6: 182 (1925)."
}
[5]=>
array(1) {
[0]=>
string(17) "Top sucıncığı"
}
}
array(6) {
[0]=>
array(1) {
[0]=>
string(108) "Achnanthes gibberula Grunow, Kongl. Svenska Vetensk.-Akad. Handl. 17(2): 121 (1880). / Kambur sucıncığı."
}
[1]=>
array(1) {
[0]=>
string(10) "Achnanthes"
}
[2]=>
array(1) {
[0]=>
string(9) "gibberula"
}
[3]=>
array(1) {
[0]=>
string(6) "Grunow"
}
[4]=>
array(1) {
[0]=>
string(55) "Kongl. Svenska Vetensk.-Akad. Handl. 17(2): 121 (1880)."
}
[5]=>
array(1) {
[0]=>
string(20) "Kambur sucıncığı"
}
}
and many more..
my regex is:
$turRegex = '/^([^\s]+)[\s]([^\s]+)[\s]([^\s]+)[,][\s]([A-Za-z].+)[\s][\/][\s](.+)[.]/m';
my foreach loop:
foreach ($data as $data) {
if (!empty(preg_match_all($turRegex, $data, $matches))) {
echo "<pre>";
var_dump($matches);
echo "</pre>";
}
}
My table name is "algeaSpecies" and columns are; "id","genusName","speciesEpiteth","author", "publication","TurkishName"
I want to insert this to genusName;
[1]=>
array(1) {
[0]=>
string(10) "Achnanthes"
this to speciesEpiteth;
[2]=>
array(1) {
[0]=>
string(8) "brevipes"
}
and others...
I'm using MySQLi
Thank you
First I noticed you used $data both as array and item in your loop.
In the following code, I assumed that you don't want the first index (the query wasn't clear).
Also, replace the DB connection credentials.
$con = new mysqli('db_host', 'username', 'password', 'db_name');
$boundArray = array_fill(0, 5, null);
$query = "INSERT INTO `algeaSpecies` (`genusName`, `speciesEpiteth`, `author`, `publication`, `TurkishName`) VALUES (?,?,?,?,?);";
$stmt = $con->prepare($query);
$stmt->bind_param("sssss", ...$boundArray);
foreach ($data as $item) {
$i = -1;
foreach ($item as $index) {
if ($i === -1) {
$i++;
continue;
}
$boundArray[$i++] = $index[0];
}
$stmt->execute();
}
$stmt->close();
$con->close();
array(2) { [0]=> array(2) { ["name"]=> string(16) "Daerah Pertanian" ["sub"]=> array(6) { [0]=> array(2) { ["name"]=> string(5) "Sawah" ["value"]=> string(3) "145" } [1]=> array(2) { ["name"]=> string(18) "Sawah Pasang Surut" ["value"]=> string(3) "455" } [2]=> array(2) { ["name"]=> string(6) "Ladang" ["value"]=> string(3) "678" } [3]=> array(2) { ["name"]=> string(10) "Perkebunan" ["value"]=> string(3) "688" } [4]=> array(2) { ["name"]=> string(19) "Perkebunan Campuran" ["value"]=> string(3) "966" } [5]=> array(2) { ["name"]=> string(16) "Tanaman Campuran" ["value"]=> string(3) "565" } } } [1]=> array(2) { ["name"]=> string(22) "Daerah Bukan Pertanian" ["sub"]=> array(2) { [0]=> array(2) { ["name"]=> string(18) "Hutan Lahan Kering" ["sub"]=> array(2) { [0]=> array(2) { ["name"]=> string(25) "Hutan Lahan Kering Primer" ["value"]=> string(3) "566" } [1]=> array(2) { ["name"]=> string(27) "Hutan Lahan Kering Sekunder" ["value"]=> string(3) "255" } } } [1]=> array(2) { ["name"]=> string(17) "Hutan Lahan Basah" ["sub"]=> array(2) { [0]=> array(1) { ["name"]=> string(24) "Hutan Lahan Basah Primer" } [1]=> array(1) { ["name"]=> string(26) "Hutan Lahan Basah Sekunder" } } } } } }
I have an array like I mention above, so I want to print out every "name" key including the index (number) of it's array parent,
for example when I print out "Tanaman Campuran" so all index parent is (0)(5) and when I print "Hutan Lahan Basah Sekunder" the index parent is (1)(1)(1)
how can I achieve it?
here is some recursive function that I've tried
$GLOBALS['all'] = '';
function printout($arr){
foreach ($arr as $ia=>$a){
if(is_array($a)){
foreach ($a as $ib=>$b){
if(is_array($b)){
printout($b);
}
else{
if ($ib == 'name') {
$GLOBALS['all'] .= $ia;
echo '<tr>';
echo '<td>' . $b . ' (' . $ia . ')</td>';
echo '</tr>';
$GLOBALS['all'] = '';
}
}
}
}
}
}
*sorry for my bad explanation, I hope you guys can understand it
You could use the following function:
function search(array $array, $name)
{
foreach ($array as $key => $entry) {
if ($entry['name'] === $name) {
return [$key];
}
if (isset($entry['sub']) && $found_keys = search($entry['sub'], $name)) {
return array_merge([$key], $found_keys);
}
}
return null;
}
It returns:
if the value was directly found, an array of one containing the associated index,
if it wasn't but was found in any descendant item, an array merging its index with the indices of said descendant,
null if it wasn't found in that part of the tree.
Note: if a given name is present several times, it will only find the first occurrence.
Demo: https://3v4l.org/1hGr1
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);
}
}
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 am trying to do a custom WP_query loop and put the results into an array of associate arrays.. It is not working too well.. I realize the array_push overwrites any arrays that have the same indexes so I have the index increment +1 in the loop so they are not identical..however it still is not working.. My results show correct only on the first index (zero).. Here is my code:
<?php
$permlink='permalink';
$excerpt='exerpt';
$title='title';
$id='id';
$finalarray=array();
for ($i = 0; $i <= 10; $i++) {
$newitem = array(array(
'id'.$i =>$id.$i,
'title'.$i => $title.$i,
'excerpt'.$i => $excerpt.$i,
'permalink'.$i => $permlink.$i
));
array_push($finalarray, $newitem);
}
$count=0;
foreach($finalarray as $item){
echo $count.':'.'<br>';
echo $item[$count]['title'.$count];
echo $item[$count]['id'.$count];
echo $item[$count]['permalink'.$count];
$count++;
}
var_dump($finalarray);
?>
Any my results show :
0:
title0id0permalink01:
2:
3:
4:
5:
6:
7:
8:
9:
10:
array(11) { [0]=> array(1) { [0]=> array(4) { ["id0"]=> string(3) "id0" ["title0"]=> string(6) "title0" ["excerpt0"]=> string(7) "exerpt0" ["permalink0"]=> string(10) "permalink0" } } [1]=> array(1) { [0]=> array(4) { ["id1"]=> string(3) "id1" ["title1"]=> string(6) "title1" ["excerpt1"]=> string(7) "exerpt1" ["permalink1"]=> string(10) "permalink1" } } [2]=> array(1) { [0]=> array(4) { ["id2"]=> string(3) "id2" ["title2"]=> string(6) "title2" ["excerpt2"]=> string(7) "exerpt2" ["permalink2"]=> string(10) "permalink2" } } [3]=> array(1) { [0]=> array(4) { ["id3"]=> string(3) "id3" ["title3"]=> string(6) "title3" ["excerpt3"]=> string(7) "exerpt3" ["permalink3"]=> string(10) "permalink3" } } [4]=> array(1) { [0]=> array(4) { ["id4"]=> string(3) "id4" ["title4"]=> string(6) "title4" ["excerpt4"]=> string(7) "exerpt4" ["permalink4"]=> string(10) "permalink4" } } [5]=> array(1) { [0]=> array(4) { ["id5"]=> string(3) "id5" ["title5"]=> string(6) "title5" ["excerpt5"]=> string(7) "exerpt5" ["permalink5"]=> string(10) "permalink5" } } [6]=> array(1) { [0]=> array(4) { ["id6"]=> string(3) "id6" ["title6"]=> string(6) "title6" ["excerpt6"]=> string(7) "exerpt6" ["permalink6"]=> string(10) "permalink6" } } [7]=> array(1) { [0]=> array(4) { ["id7"]=> string(3) "id7" ["title7"]=> string(6) "title7" ["excerpt7"]=> string(7) "exerpt7" ["permalink7"]=> string(10) "permalink7" } } [8]=> array(1) { [0]=> array(4) { ["id8"]=> string(3) "id8" ["title8"]=> string(6) "title8" ["excerpt8"]=> string(7) "exerpt8" ["permalink8"]=> string(10) "permalink8" } } [9]=> array(1) { [0]=> array(4) { ["id9"]=> string(3) "id9" ["title9"]=> string(6) "title9" ["excerpt9"]=> string(7) "exerpt9" ["permalink9"]=> string(10) "permalink9" } } [10]=> array(1) { [0]=> array(4) { ["id10"]=> string(4) "id10" ["title10"]=> string(7) "title10" ["excerpt10"]=> string(8) "exerpt10" ["permalink10"]=> string(11) "permalink10" } } }
So it looks like the values are in the array, however, only the first index ( zero ) prints correctly.. any suggestions? Also, is there any way i can push an associate array and it not be over written so I dont have to increment the index?
There are a few problems here.
for ($i = 0; $i <= 10; $i++) {
$newitem = array(array(
'id'.$i =>$id.$i,
'title'.$i => $title.$i,
'excerpt'.$i => $excerpt.$i,
'permalink'.$i => $permlink.$i
));
array_push($finalarray, $newitem);
}
You are pushing an array, containing an array, containing 4 elements into $finalarray. There is no need for the outer array(). You can just do $newitem = array(...). array_push appends to end of the array, incrementing the index for you.
Second, in your foreach, your $count variable is not needed at all. When using foreach, $item is the element of the array. No need to look it up by the index.
If you want the index, however, foreach can give it to you.
foreach($finalarray as $count=>$item){
echo $count.':'.'<br>';
echo $item['title'.$count];
echo $item['id'.$count];
echo $item['permalink'.$count];
}
Your original code wasn't working because in each $item there was one array. That array had one item. In each element, the inner aray was always at index 0. Incrementing $count made it so only the 1st element worked, the others didn't because $item[1] didn't exist, it was always $item[0].
for ($i = 0; $i <= 10; $i++) {
$newitem = array(array(
'id'.$i =>$id.$i,
'title'.$i => $title.$i,
'excerpt'.$i => $excerpt.$i,
'permalink'.$i => $permlink.$i
));
$finalarray[] = $newitem;
unset($newitem);
}
Since you don't care about the key of the final array just add it on using $finalarray[]