Foreach a specific key from array - php

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
)

Related

How to create variables using a php array?

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;

PHP get the name of arrays in multidimensional array

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
}

Laravel/PHP create an array from array

Hey guys I'm confused about how to create an array using specific keys from my pre-existing array.
Laravel controller
public function index()
{
$content = Page::find(1)->content->toArray();
return View::make('frontend.services', compact('content'));
}
$content is an array that looks similar to
array (
0 => array (
'id' => '1',
'page_id' => '1',
'name' => 'banner_heading',
'content' => 'some content', ),
1 => array (
'id' => '2',
'page_id' => '1',
'name' => 'banner_text',
'content' => 'some other content' )
)
And I want it recreate this array to look like this
array (
0 => array (
'banner_heading' => 'some content'
),
1 => array (
'banner_text' => 'some other content'
)
)
How can I move the keys name and content to equal their values as a single row in the array?
I greatly appreciate any advice.
PHP >= 5.5.0:
$result = array_column($content, 'content', 'name');
PHP < 5.5.0:
foreach($content as $key => $array) {
$result[$key] = array($array['name'] => $array['content']);
}
You mean
$newContent = array();
foreach ($content as $record) {
$newContent[] = array($record['name'] => $record['content']);
}
?
I don't know Laravel, but i believe that your solutions should be similar to this :
$newArray= array();
foreach($content as $key => $value)
{
$newArray[] = $value["banner_heading"];
}
return View::make('frontend.services', compact('newArray'));
Or at least it should be something similar with this.

Access multidimensional array without multiple loops

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

multidimensional array - adding a key and value where a key and value is matched

I'm trying to add a key and value (associative) from an array to another array, where one specific key and value match. Here are the two arrays:
$array1 = array(
1 => array(
'walgreens' => 'location',
'apples' => 'product1',
'oranges' => 'product2'
),
2 => array(
'walmart' => 'location',
'apples' => 'product1',
'oranges' => 'product2',
'milk' => 'product3'
)
);
$array2 = array(
1 => array(
'walgreens' => 'location',
'apples' => 'product1',
'oranges' => 'product2',
'bananas' => 'product3',
)
);
Here is the attempt I made at modifying $array1 to have key 'bananas' and value 'product3':
$dataCJ = getCJItem($isbn);
foreach ($array1 as $subKey => $subArray) {
foreach($subArray as $dkey => $dval){
foreach($array2 as $cjk => $cjv){
foreach($cjv as $cjkey => $cjval){
if($dval['walgreens'] == $cjval['walgreens']){
$dval['bananas'] = $cjval['bananas'];
}
}
}
}
}
This doesn't work. How can I fix this?
Change => $dval to => &$dval. Currently you are creating and writing to a new variable and the update will not work in-place.
I would look at array_merge() function!
Here is a start with the PHP doc.
For your specific case, you could do the following :
foreach($array1 as $key1 => $values1){
foreach($array2 as $key2 => $values2){
if($values1[0] == $values2[0]){
$array1[$key1] = array_merge($values1, $values2);
}
}
}
Note to simplify the problem you should inverse the first key=> value pair of the array.
Having an array this way would be a lot simper :
array(
'location' => "The location (eg:walgreens)",
//...
);
This way you could change the comparison to the following instead :
$values1['location'] == $values2['location']
Which would be safer in the case the array is not built with the location as the first pair.

Categories