Foreach array organization/iteration - php

I have this array that I've tried iterating over and creating a new array:
array(233) {
[0]=>
array(2) {
["subject_id"]=>
int(138)
["relatedsubject_id"]=>
int(127)
}
[1]=>
array(2) {
["subject_id"]=>
int(138)
["relatedsubject_id"]=>
int(47)
}
[2]=>
array(2) {
["subject_id"]=>
int(138)
["relatedsubject_id"]=>
int(13)
}
[3]=>
array(2) {
["subject_id"]=>
int(138)
["relatedsubject_id"]=>
int(56)
}
[4]=>
array(2) {
["subject_id"]=>
int(154)
["relatedsubject_id"]=>
int(77)
}
[5]=>
array(2) {
["subject_id"]=>
int(154)
["relatedsubject_id"]=>
int(69)
}
[6]=>
array(2) {
["subject_id"]=>
int(154)
["relatedsubject_id"]=>
int(70)
}
[7]=>
array(2) {
["subject_id"]=>
int(154)
["relatedsubject_id"]=>
int(75)
I cut it short so it's not too obnoxious. This is the code I'm using now:
$subject_id = array();
foreach ($results as $mainKey => $subArrays) {
if(!isset($subject_id[$results[$mainKey]["subject_id"]])) {
$subject_id[$results[$mainKey]["subject_id"]] = array();
array_push($subject_id[$results[$mainKey]["subject_id"]], $results[$mainKey]["relatedsubject_id"]);
// $subject_id[$results[$mainKey]["subject_id"]][] = $results[$mainKey]["relatedsubject_id"];
}
}
var_dump($subject_id);
My results look like this:
array(111) {
[138]=>
array(1) {
[0]=>
int(127)
}
[154]=>
array(1) {
[0]=>
int(77)
}
Any ideas on why I'm only getting 1 value and how to modify to get each "relatedsubject_id" to fall in line with the corresponding "subject_id"? Thank you.
Edit
Expected Result:
array {
[138]=>
array(1) {
[0]=>
int(127)
[1]=>
int(47)
[2]=>
int(13)
[3]=>
int(56)
}
[154]=>
array(1) {
[0]=>
int(77)
[1]=>
int(69)
[2]=>
int(70)
[3]=>
int(75)
}

It seems you are trying to consolidate your subject ids and relatedsubject_ids. If thats the case, this may work for you.
$subject_id = array();
foreach ($results as $mainKey => $subArrays) {
if(!isset($subject_id[$results[$mainKey]['subject_id']])) {
$subject_id[$results[$mainKey]['subject_id']] = array('subject_id' => $results[$mainKey]['subject_id'], 'relatedsubject_id' => array());
}
$subject_id[$results[$mainKey]['subject_id']]['relatedsubject_id'][] = $results[$mainKey]["relatedsubject_id"];
}
Changed to your EDIT
$subject_id = array();
foreach ($results as $mainKey => $subArrays) {
if(!isset($subject_id[$results[$mainKey]['subject_id']])) {
$subject_id[$results[$mainKey]['subject_id']] = array();
}
$subject_id[$results[$mainKey]['subject_id']][] = $results[$mainKey]["relatedsubject_id"];
}
The reason why you were only getting one result is you had all your code in the if(!isset()) function. That should only not be set once. If that makes sense.

Related

How can I merge array of arrays fetched from database?

I fetched all codes user got from the database and they are returned as arrays of arrays.
How could I merge them so that the codes were sequentially in a one-dimensional array?
Unfortunately, I can't change query of the procedure:
Code:
function loadGlobalPermissions(){
global $pdo;
$user_id = $_SESSION['id'];
$sql="CALL skaj_listp(:user_id)";
$statement = $pdo->prepare($sql);
$statement->bindParam(':user_id',$user_id,PDO::PARAM_STR);
if($statement->execute()){
$response[] = $statement->fetchALL(PDO::FETCH_ASSOC);
}
return $response;
}
Array:
array(1) { [0]=> array(1) { [0]=> array(28) { [0]=> array(1) { ["kod"]=> string(2) "DR" } [1]=> array(1) { ["kod"]=> string(3) "DRW" } [2]=> array(1) { ["kod"]=> string(2) "ER" } [3]=> array(1) { ["kod"]=> string(4) "ERDD" } [4]=> array(1) { ["kod"]=> string(5) "ERDSP" } [5]=> array(1) { ["kod"]=> string(4) "ERED" } [6]=> array(1) { ["kod"]=> string(5) "EREFP" } [7]=> array(1) { ["kod"]=> string(4) "EREM" } [8]=> array(1) { ["kod"]=> string(5) "EREMA" } [9]=> array(1) { ["kod"]=> string(4) "EREO" } [10]=> array(1) { ["kod"]=> string(4) "EREP" } [11]=> array(1) { ["kod"]=> string(4) "ERES" } [12]=> array(1) { ["kod"]=> string(4) "ERET" } [13]=> array(1) { ["kod"]=> string(4) "EREU" } [14]=> array(1) { ["kod"]=> string(5) "EREWM" } [15]=> array(1) { ["kod"]=> string(4) "ERUD" } [16]=> array(1) { ["kod"]=> string(5) "ERUSP" } [17]=> array(1) { ["kod"]=> string(2) "EU" } [18]=> array(1) { ["kod"]=> string(3) "EUS" } [19]=> array(1) { ["kod"]=> string(6) "EUSEUP" } [20]=> array(1) { ["kod"]=> string(3) "EWR" } [21]=> array(1) { ["kod"]=> string(3) "LRW" } [22]=> array(1) { ["kod"]=> string(5) "LUDDG" } [23]=> array(1) { ["kod"]=> string(5) "LUUZG" } [24]=> array(1) { ["kod"]=> string(3) "LUW" } [25]=> array(1) { ["kod"]=> string(2) "UR" } [26]=> array(1) { ["kod"]=> string(2) "UW" } [27]=> array(1) { ["kod"]=> string(3) "WPA" } } } } string(4)
Here's a function i wrote for you to merge a multidimensional array of any depth and return a one-dimensional array. Use it to merge your multidimensional array:
function mergeMultidimensionalArray($array, $merged = [], $depth = 0)
{
foreach($array as $key => $value) {
if(is_array($value)) {
$merged = mergeMultidimensionalArray($value, $merged, ++$depth);
} else {
if(isset($merged[$key])) {
$merged[$key . $depth] = $value;
} else {
$merged[$key] = $value;
}
}
}
return $merged;
}
$merged = mergeMultidimensionalArray($response);

Insert PHP Regex Exploded Array Into MySQL Table

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

how to get the index of every array on multidimensional array with unknown depth in php

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

Optimizing PHP code with two foreach loops

I have an array that consists of the keys:
$countries = ['EU', 'UK', 'Asia'];
Another array that consists of further elements based on those keys:
$countries_array=['UK'=>['London', 'Birmingham', 'Manchester'], 'EU'=> ['Germany','Netherlands'] , 'Asia'=> ['Pakistan','Bangladesh','China']];
$mid_countries[];
I want to pass through all the elements, check if they are empty or not and then further create another array. I have written a code and it works fine. But it has foreach loops. Is there any way that I could optimize this code?
foreach ($countries as $each_country) {
if (!empty($countries_array["$each_country"][0])) {
foreach ($countries_array["$each_country"] as $value) {
$mid_countries[] = array("wildcard" => array("$each_country" => $value. "*"));
}
}
}
Expected result:
array(8) {
[0]=> array(1) { ["wildcard"]=> array(1) { ["EU"]=> string(8) "Germany*" } } [1]=> array(1) { ["wildcard"]=> array(1) { ["EU"]=> string(12) "Netherlands*"}}
[2]=> array(1) { ["wildcard"]=> array(1) { ["UK"]=> string(7) "London*" } } [3]=> array(1) { ["wildcard"]=> array(1) { ["UK"]=> string(11) "Birmingham*" } } [4]=> array(1) { ["wildcard"]=> array(1) { ["UK"]=> string(11) "Manchester*" } } [5]=> array(1) { ["wildcard"]=> array(1) { ["Asia"]=> string(9) "Pakistan*" } } [6]=> array(1) { ["wildcard"]=> array(1) { ["Asia"]=> string(11) "Bangladesh*"}}
[7]=> array(1) { ["wildcard"]=> array(1) { ["Asia"]=> string(6) "China*" } } }
I think you expected this (Code updated use its working in single loop)
foreach ($countries_array as $key=>$value) {
$tmp=implode('*#'.$key.'#',$value);
$tmp='#'.$key.'#'.$tmp."*";
$tmp=str_replace('#'.$key.'#',"\"}},{\"wildcard\":{\"".$key."\":\"",$tmp);
$result=$result.substr($tmp,3)."\"}}";
}
$result="[".ltrim($result,"\"}},")."]";
$result=json_decode($result,true);
print_r($result);

Foreach creating multi-level instead of single level array in PHP

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;

Categories