PHP Going through array? - php

I have a $search_array like this
Array
(
[1] => Array
(
[type] => book
[search] => steve
)
[2] => Array
(
[type] => book
[search] => john
)
foreach ($search_array as $s) {
$arrayid = //???????
$searchtype = $s['type'];
$search = urlencode($s['search']);
getResult($arrayid);
}
I'm trying to figure out how to get the array number. So for the first result i need $arrayid to be 1. How do I reference that in the foreach loop?
Thanks

Use a foreach with "$key => $value"
Array
(
[1] => Array
(
[type] => book
[search] => steve
)
[2] => Array
(
[type] => book
[search] => john
)
foreach ($search_array as $key => $s) {
$arrayid = $key
$searchtype = $s['type'];
$search = urlencode($s['search']);
getResult($arrayid);
}

Adding $arrayid => in your foreach loop declaration will auto-assign $arrayid with the current array index.
foreach ($search_array as $arrayid => $s) {
// ...
getResult($arrayid);
}
See foreach on PHP Manual.

foreach ($search_array as $arrayid => $s) {
Please read PHP documentation before asking such basic questions

foreach ($search_array as $arrayid => $s) {
// your code here
}

This is a way you could retrieve data from a Php array. It will retrieve all entries from array $value and their key $key.
foreach ($array as $key => $value) {
// $key is the array index
}

Related

How to parse arrays with different levels PHP

In a foreach loop i would like to compare [name] value beetween different arrays but they have not the same levels.
Array(
[array1] => Array
(
[0] => WP_Term Object
(
[name] => Plafond
)
)
[array2] => WP_Term Object
(
[name] => Chaudière
)
[array3] => Array
(
[0] => WP_Term Object
(
[name] => Pla
)
[1] => WP_Term Object
(
[name] => Toc
)
)
)
I don't know how could i get the [name] in the same loop whereas levels are different.
I have tried to make :
foreach( $fields as $name => $value )
{
echo $value->name; }
Should i add another loop in the first loop ?
thanks
So your data looks like this:
$json = '{"array1":[{"name":"Plafond"}],"array2":{"name":"Chaudière"},"array3":[{"name":"Pla"},{"name":"Toc"}]}';
$array = json_decode($json);
If you don't know how deep it will go, a simple recursive function should work. Perhaps something like this:
function get_name($o, &$output) {
if (is_array($o)) {
foreach($o as $v) {
get_name($v, $output);
}
} elseif (property_exists($o, "name")) {
$output[] = $o->name;
}
}
$output = [];
foreach ($array as $v) {
get_name($v, $output);
}
If you data is going to look like the sample you provided (i.e. it will always be first or second level) then you don't need to worry about recursion.
$output = [];
foreach ($array as $k=>$v) {
if (is_array($v)) {
foreach ($v as $k2=>$v2) {
$output[] = $v2->name;
}
} else {
$output[] = $v->name;
}
}
Either way, your output values are all in the $output array:
print_r($output);
Output:
Array
(
[0] => Plafond
[1] => Chaudière
[2] => Pla
[3] => Toc
)
You can use array_map, array_key_exists to retrive the name index from the array
$jsonFormat = '{"array1":[{"name":"Plafond"}],"array2":{"name":"Chaudière"},"array3":[{"name":"Pla"},{"name":"Toc"}]}';
$jsonArray = json_decode($jsonFormat,true);
$res = [];
array_map(function($v) use (&$res){
if(array_key_exists('name', $v)){
$res[] = $v['name'];
}else{
foreach($v as $_key => $_value){
$res[] = $_value['name'];
}
}
}, $jsonArray);
echo '<pre>';
print_r($res);
Result:-
Array
(
[0] => Plafond
[1] => Chaudière
[2] => Pla
[3] => Toc
)
You can use $res to compare the names.

I have only one array inside the index, so i want to move the index to the previous index? Please see the reference below:

Array
(
[data] => Array
(
[0] => Array
(
['degree_level'] => Bachelor's
)
[1] => Array
(
['field_of_study'] => Science
)
[2] => Array
(
['grade_point'] => 3
)
[3] => Array
(
['criteria'] => desired
)
)
)
What I want :
Array
(
[data] => Array
(
['degree_level'] => Bachelor's
['field_of_study'] => Science
['grade_point'] => 3
['criteria'] => desired
)
)
You should use array_flatten(); to achieve your goal like this,
$flattened = array_flatten(Your_Data_Array);
Please give it a try and let me know.
UPDATE
$flattened = array_map(function($item) {
return $item[0];
}, Your_Data_Array);
For more information you can visit this for PHP functions.
Let me know in case of any queries.
$output = array_map(function($item) { return $item[0]; }, $myArray);
Try this,
foreach($data as $key1=>$val1){
foreach($val1 as $key2=>$val2){
$new_array[$key2] = $val2;
}
}
You can do it by loop.
foreach ($data as $key => $value) {
foreach ($value as $key1 => $value2) {
$data[$key1] = $value2;
}
}
You could use for example a double foreach loop to use the key and the value from the second loop and add those to the $arrays["data"] array.
Then you could use unset to remove the nested arrays.
$arrays = [
"data" => [
["degree_level" => " Bachelor's"],
["field_of_study" => "Science"],
["grade_point" => 3],
["criteria" => "desired"]
]
];
foreach($arrays["data"] as $dataKey => $data) {
foreach ($data as $key => $value) {
$arrays["data"][$key] = $value;
}
unset($arrays["data"][$dataKey]);
}
print_r($arrays);
That would give you:
Array
(
[data] => Array
(
[degree_level] => Bachelor's
[field_of_study] => Science
[grade_point] => 3
[criteria] => desired
)
)
Demo
you can achieve this using array_collapse.
Link
EDIT :
while tag has changed.
Here is the core php solution based on Laravel array_collapse:
function collapse($array)
{
$results = [];
foreach ($array as $values) {
if (! is_array($values)) {
continue;
}
$results = array_merge($results, $values);
}
return $results;
}

Nested 'foreach' for multidimensional array

<?php
$p_23 = array("Name"=>"XYZ","Age"=>"12");
$a_23 = array("Class"=>"5","Sec"=>"A");
$r_23 = array("Personal"=>$p_23,"Academic"=>$a_23);
$p_24 = array("Name"=>"ABC","Age"=>"14");
$a_24 = array("Class"=>"6","Sec"=>"B");
$r_24 = array("Personal"=>$p_24,"Academic"=>$a_24);
$stud = array("23"=>$r_23,"24"=>$r_24);
foreach ($stud as $key => $value) {
echo $value;
}
?>
Using echo is giving error,
previous issue resolved, expanding my question now.
now i want this multi dimensional array to print like below using html tags
#Roll 23#
##Academic##
-Class=>5
-sec=>B
Personal
-Name=>YXZ
-Age=>12
#Roll 24#
##Academic##
-Class=>6
-sec=>A
Personal
-Name=>ABC
-Age=>12
--Nested foreach part with HTML tags--
foreach ($stud as $key => $value) {
echo "<h1>Roll $key</h1>";
echo "<ol>";
foreach ($r_23 as $key => $value) {
echo "<h2>$key</h2>";
echo "<ul>";
foreach ($p_23 as $key => $value){
echo "<li>$key => $value</li>";}
echo "</ul>";}
echo "</ol>";
but it is showing the same value for both academic and personal keys, which i dont exactly want. Thank u!!
$value is an array, echo will only print strings, you need to either JSON encode your $value and echo it or use var_dump. If your intended output was more complex than this then you would need to expand on your question.
Well, its a multi-dimensional array, so you need more foreach()
Here is the updated code:
<?php
$p_23 = array("Name"=>"XYZ","Age"=>"12");
$a_23 = array("Class"=>"5","Sec"=>"A");
$r_23 = array("Personal"=>$p_23,"Academic"=>$a_23);
$p_24 = array("Name"=>"ABC","Age"=>"14");
$a_24 = array("Class"=>"6","Sec"=>"B");
$r_24 = array("Personal"=>$p_24,"Academic"=>$a_24);
$stud = array("23"=>$r_23,"24"=>$r_24);
foreach ($stud as $key => $value) {
foreach($value as $k => $v){
foreach($v as $kk => $vv) {
echo $vv;
}
}
}
?>
And this is your multi-dimensional array:
Array
(
[23] => Array
(
[Personal] => Array
(
[Name] => XYZ
[Age] => 12
)
[Academic] => Array
(
[Class] => 5
[Sec] => A
)
)
[24] => Array
(
[Personal] => Array
(
[Name] => ABC
[Age] => 14
)
[Academic] => Array
(
[Class] => 6
[Sec] => B
)
)
)

PHP array refactoring

I'm banging my head against what I am sure is a simple fix to re-structure an array. I don't have any choice over how the array is given to me:
Array
(
[author] => Array
(
[0] => John Doe
)
[journal] => Array
(
[0] => Biology
)
)
But I need the following:
Array
(
[author] => John Doe
[journal] => Biology
)
I've been working on various routes, but my brain doesn't work like this right now...
$result = [];
foreach ($data as $key => $value) {
$result[$key] = $value[0];
}
var_dump($result);
<?php
function reduce_array($array) {
$new = array();
foreach($array as $key => $value) {
$new[$key] = $value[0];
}
return $new;
}
?>

php how to create a foreach loop?

Array
(
[0] => Array
(
[id] =>
[test] => 145198
[defender] => 5590478
[stake] => 107
[game_id] =>
)
[1] => Array
(
[id] =>
[test] => 145198
[defender] => 5590478
[stake] => 107
[game_id] =>
)
how to do a foreach loop for it?
so far i have:
$mresults = $game_set->get_it();
foreach ($mresults as $key => $row)
{ ...dosomething}
but i believe i need to do another one inside this one.
any ideas?
thanks
Your foreach assigns the nested array to the $row variable and can be accessed like:
$row["test"]
$row["id"]
If you wish to loop again, you can do:
$mresults = $game_set->get_it();
foreach ($mresults as $key => $row)
{
foreach($row as $k => $v)
{
echo $k." = ".$v;
}
}
Don't know what you want to do, but try:
$mresults = $game_set->get_it();
foreach ($mresults as $key => $row) {
echo "key: $key, row: $row\n";
}
To see how it works.
In your case, $row will contain that inner array, so you can output those values using $row['test'], $row['defender'], etc.
Most likely this is all you need:
foreach ($game_set->get_it() as $game)
{
echo $game['defender']."\n";
}

Categories