I have a PHP array, something like below:
Array(
[0] => Array
(
[name] => month_year
[value] => 201609
)
[1] => Array
(
[name] => advance_amount
[value] => 50%
)
)
Using this array, I want to create 2 variables like this:
$month_year = '201609';
$advance_amount = '50%';
Can anybody tell me is this possible in php?
I tried it using two foreach but I don't have any idea how to precced.
foreach ($_POST as $k => $data) {
//echo "<pre>", print_r($data)."</pre>";
foreach ($data as $key => $value) {
echo $key."<br>";
}
}
Use variable variables. Your foreach loop should be like this:
foreach ($_POST as $k => $data) {
$$data['name'] = $data['value'];
}
// display variables
echo $month_year . "<br />";
echo $advance_amount;
PHP7 style:
$a = [['name' = 'month_year', 'value' => '201609'], ['name' => 'advance_amount', 'value' => '50%']];
foreach ($a as $line) {
${$line['name']} = $line['value'];
}
php > echo $month_year; //201609
Have a look at the Variables reference
Caution
Further dereferencing a variable property that is an array has
different semantics between PHP 5 and PHP 7. The PHP 7.0 migration
guide includes further details on the types of expressions that have
changed, and how to place curly braces to avoid ambiguity.
using list it gives you the cleaner way to solve the issue: for example
$data = [
[
'name' => 'month_year',
'value' => 201609
],
[
'name' => 'advance_amount',
'value' => '50%'
]
];
list($month_year, $advance_amount) = array_map(function($value){
return $value['value'];
}, $data);
echo sprintf('Month of the year is %s with porcentage %s', $month_year, $advance_amount);
This will have the result you are looking for with a clearer code.
Month of the year is 201609 with porcentage 50%
first create loop and declare var.
$data = array(array(
'name' => 'month_year',
'value' => 201609,
), array(
'name' => 'advance_amount',
'value' => '50%',
)
);
foreach ($data as $key => $value) {
${$value['name']} = $value['value'];
}
echo $month_year;
echo '<br>';
echo $advance_amount;
Related
I have a very simple multidimensional array and some PHP code. The code should print the p_id values, but it does not do it. Do I really have to add one foreach more or is there other ways?
And here is the array:
Array (
[2764] => Array (
[status] => 0
[0] => Array (
[p_id] => 2895
)
[1] => Array (
[p_id] => 1468
)
)
[5974] => Array (
[status] => 0
[0] => Array (
[p_id] => 145
)
[1] => Array (
[p_id] => 756
)
)
)
Here is my PHP code:
foreach($arr as $innerArray)
foreach($innerArray as $key => $value)
echo $key . "=>" . $value . "<br>";
It prints:
status=>0
0=>Array
1=>Array
status=>0
0=>Array
1=>Array
foreach($arr as $a => $a_value)
{
echo $a . '<br>';
foreach($a_value as $av_arr => $av)
{
if(!is_array($av))
{
echo $av_arr . '=>' . $av . '<br>';
}
else
{
foreach($av as $inner_av => $inner_av_val)
{
echo $inner_av . '=>' . $inner_av_val . '<br>';
}
}
}
}
This simple call to array_walk_recursive() produces the output requested in the question:
array_walk_recursive(
$arr,
function ($value, $key) {
echo $key . "=>" . $value . "<br>";
}
);
But it doesn't make much sense as the output mixes the values of status with the values of p_id.
I would go for a more structured display using the original code with a little more meaning for the names of the variables:
foreach ($arr as $catId => $catInfo) {
// Category ID and details; use other names if I'm wrong
printf("Category: %d (status: %s)\n", $catId, $catInfo['status'] ? 'active' : 'inactive');
foreach ($catInfo as $key => $value) {
if ($key == 'status') {
// Ignore the status; it was already displayed
continue;
}
foreach ($value as $prodInfo) {
printf(" Product ID: %d\n", $prodInfo['p_id']);
}
}
}
The structure of the input array tells me you should first fix the code that generates it. It should group all the products (the values that are now indexed by numeric keys) into a single array. It should look like this:
$input = array(
'2764' => array(
'status' => 0,
'products' => array(
2895 => array(
'p_id' => 2895,
'name' => 'product #1',
// more product details here, if needd
),
1468 => array(
'p_id' => 1468,
'name' => 'product #2',
),
// more products here
),
// more categories here
),
Then the code that prints it will look like this:
foreach ($arr as $catId => $catInfo) {
// Category ID and details; use other names if I'm wrong
printf("Category: %d (status: %s)\n", $catId, $catInfo['status'] ? 'active' : 'inactive');
foreach ($catInfo['products'] as $prodInfo) {
printf(" %s (ID: %d)\n", $prodInfo['name'], $prodInfo['p_id']);
// etc.
}
}
Use a recursive function:
function printIds($arr) {
foreach ($arr as $key => $val) {
if (is_array($val) && array_key_exists("p_id", $val)) {
echo $val["p_id"]."\n";
} elseif(is_array($val)) {
printIds($val);
}
}
}
Working example:
$arr = [
2764 => [
'status' => 0,
['p_id' => 100],
],
4544 => [
'status' => 0,
['p_id' => 100],
],
['p_id' => 100],
];
function printIds($arr) {
foreach ($arr as $key => $val) {
if (is_array($val) && array_key_exists("p_id", $val)) {
echo $val["p_id"]"\n";
} elseif(is_array($val)) {
printIds($val);
}
}
}
printIds($arr);
The function loops all entries of a given array and echo's them out, if they contain an array with a key named "p_id". If it does find a nested array, then it does loop also all child arrays.
I have a simple multidimensional array with two other arrays in it.
<?php
$data = array(
'first_array' => array(
'name' => 'Test1',
'description' => '...',
),
'second_array' => array(
'title' => 'Test2',
'description' => '...',
)
);
?>
And I have a simple foreach array like this:
function show($data, $id){
foreach ($data as $course) {
}
}
How can I display (and get) the name of the array in every iteration (I mean if it is 'first_array' or 'second_array', not the name fields in the arrays).
Use key=>val syntax
foreach ($data as $key=>$course) {
echo $key;
}
use this syntax for foreach :
foreach ($data as $name => $course) {
//do sth
}
I have an array that looks like this:
[0] => Array
(
[name] => typeOfMusic
[value] => this_music_choice
)
[1] => Array
(
[name] => myMusicChoice
[value] => 9
)
[2] => Array
(
[name] => myMusicChoice
[value] => 8
)
I would like to reform this into something with roughly the following structure:
Array(
"typeOfMusic" => "this_music_choice",
"myMusicChoice" => array(9, 8)
)
I have written the following but it doesn't work:
foreach($originalArray as $key => $value) {
if( !empty($return[$value["name"]]) ){
$return[$value["name"]][] = $value["value"];
} else {
$return[$value["name"]] = $value["value"];
}
}
return $return;
I've tried lots of different combinations to try and get this working. My original array could contain several sets of keys that need converting to arrays (i.e. it's not always going to be just "myMusicChoice" that needs converting to an array) ?
I'm getting nowhere with this and would appreciate a little help. Many thanks.
You just need to loop over the data and create a new array with the name/value. If you see a repeat name, then change the value into an array.
Something like this:
$return = array();
foreach($originalArray as $data){
if(!isset($return[$data['name']])){
// This is the first time we've seen this name,
// it's not in $return, so let's add it
$return[$data['name']] = $data['value'];
}
elseif(!is_array($return[$data['name']])){
// We've seen this key before, but it's not already an array
// let's convert it to an array
$return[$data['name']] = array($return[$data['name']], $data['value']);
}
else{
// We've seen this key before, so let's just add to the array
$return[$data['name']][] = $data['value'];
}
}
DEMO: https://eval.in/173852
Here's a clean solution, which uses array_reduce
$a = [
[
'name' => 'typeOfMusic',
'value' => 'this_music_choice'
],
[
'name' => 'myMusicChoice',
'value' => 9
],
[
'name' => 'myMusicChoice',
'value' => 8
]
];
$r = array_reduce($a, function(&$array, $item){
// Has this key been initialized yet?
if (empty($array[$item['name']])) {
$array[$item['name']] = [];
}
$array[$item['name']][] = $item['value'];
return $array;
}, []);
$arr = array(
0 => array(
'name' => 'typeOfMusic',
'value' => 'this_music_choice'
),
1 => array(
'name' => 'myMusicChoice',
'value' => 9
),
2 => array(
'name' => 'myMusicChoice',
'value' => 8
)
);
$newArr = array();
$name = 'name';
$value = 'value';
$x = 0;
foreach($arr as $row) {
if ($x == 0) {
$newArr[$row[$$name]] = $row[$$value];
} else {
if (! is_array($newArr[$row[$$name]])) {
$newArr[$row[$$name]] = array();
}
array_push($newArr[$row[$$name]], $row[$$value]);
}
$x++;
}
Let's say I have an array formatted like so:
$data = array(
'variables' => array(
'823h9fhs9df38h4f8h' => array(
'name' => 'Foo',
'value' => 'green'
),
'sdfj93248fhfhf88rh' => array(
'name' => 'Bar',
'value' => 'red'
)
)
);
Say I wanted to access the name & values of each array in the variables array. Surely you can access it just looping over the main variables array and not looping over each individual item array? Something like so?
foreach ($data as $k => $v) {
$name = $data['variables'][0]['name'];
}
I'm sure I'm missing something simple...
You can do
foreach ($data['variables'] as $k => $v) {
$name = $v['name'];
}
You can also try this
create a new array containing just the names..
$new_arr = array_column($data['variables'],'name' );
echo $new_arr[0].'<br/>';
echo $new_arr[1].'<br/>';
I have an array with 2 same keys i want to foreach out if possible. The currently code looks like:
$arrayName = array(
1 => array('detail' => 'detail1' , 'detail' => 'detail2')
);
foreach ($arrayName[1] as $key['detail'] => $value) {
echo $value;
}
Thanks for any help!
Your keys are overwriting themselves. You may want to approach the solution like this:
$arrayName = array(
array('name' => 'detail' , 'value' => 'detail1'),
array('name' => 'detail' , 'value' => 'detail2')
);
foreach ($arrayName as $i) {
echo $i['value'];
}
You cannot have identical keys for an array.. The final key overwrites the first one. (in your case)
From the PHP Docs..
If multiple elements in the array declaration use the same key, only
the last one will be used as all others are overwritten.
A dynamic way of doing this..
<?php
$new_arr = array();
foreach(range(1,5) as $v)
{
$new_arr['detail'.$v]='detail'.$v;
}
print_r($new_arr);
OUTPUT :
Array
(
[detail1] => detail1
[detail2] => detail2
[detail3] => detail3
[detail4] => detail4
[detail5] => detail5
)