PHP array with foreach - php

I'm trying to get two key values and add them both to a foreach. I can't seem to get it to work. Any help will be appreciated.
So I have an array that looks like this:
(
[0] => Array
(
[Code1] => M22
[Code2] => M33
[Code3] => S44
)
[1] => Array
(
[Code1] => E22
[Code2] => E33
[Code3] => E44
)
)
How can I search in the array and get the key and values for
Code2 & Code3 and add both of them to a foraeach?
I can get the Code3 by doing this. This works for the last array element using "array_pop" but can't figure out how to get Code2.
// Filter and get the Code3
$pcodes = array_map('array_pop', $this->dpparent);
foreach ($pcodes as $parent_code) {
echo "\r\n". $parent_code;
}

The simplest way is probably a double for loop:
foreach ($data as $subarray) {
foreach ($subarray as $key => $value) {
if (in_array($key, ['Code2', 'Code3'], true)) {
// Logic here
}
}
}

If you know the name of the keys, then you can use array_column to extract the values:
$code2values = array_column($data, 'Code2');
$code3values = array_column($data, 'Code3');
foreach ($code2values as $key => $code2) {
$code3 = $code3values[$key];
// do something with $code2 and $code3
echo "code2: $code2, code3: $code3\n";
}
Output (for your sample data):
code2: M33, code3: S44
code2: E33, code3: E44
Demo on 3v4l.org

Related

Values From Multi-Row MySQL To Single Array

Fetching multi-row data from MySQL database and trying to convert the results into a single array. Since the data is coming from a custom function where modifying it will break many other things, I can't change the way the way it is fetched so must process after retrieval using PHP. This is a sample:
Array
(
[0] => Array
(
[FieldLabel] =>
[FieldName] => ID
[FieldValue] => $ID
[FieldType] => 0
)
[1] => Array
(
[FieldLabel] => Name
[FieldName] => Name
[FieldValue] => $FieldName
[FieldType] => 1
)
)
Looking for something like this with only all the values in a single array but with the variables populated:
Array('','ID',$ID,0,'Name','Name',$FieldName,1)
I found this little function in another post that seemed would at lease create the array it but unfortunately it does not and I don't know enough about array manipulation to be able to sort it out. Any ideas?
function array2Recursive($array) {
$lst = array();
foreach( array_keys($array) as $k ) :
$v = $array[$k];
if (is_scalar($v)) :
$lst[] = $v;
elseif (is_array($v)) :
$lst = array_merge($lst,array2Recursive($v));
endif;
endforeach;
return array_values(array_unique($lst));
}
On way to solve this could be to use a foreach to loop through the items and add them to an array:
$result = [];
foreach ($array as $a) {
foreach($a as $item) {
$result[] = $item;
}
}
print_r($result);
Demo

How to get a value from an array

Not sure why I can't this to work. My json is:
[values] => Array
(
[0] => Array
(
[field] => id1
[value] => 985
)
[1] => Array
(
[field] => id2
[value] => 6395
)
[2] => Array
(
[field] => memo
[value] => abcde
)
I simply want the values of id2
I tried:
foreach ($json['values'] as $values) {
foreach ($json as $key=>$data) {
if ($data['field'] == 'id2') {
$result = $data['value'];
print '<br>value: '.$result;
}
}
}
Thanks. I know this should be relatively simple and I'm sure I've done this correctly before.
there's no need for inner loop, after the first one $values already contain the exact array that you are looking for
foreach ($json['values'] as $values) // $values contain
{
if ($values['field'] == 'id2')
{
$result = $values['value'];
print '<br>value: '.$result;
}
}
foreach ($json['values'] as $values) { //you're looping your first array, puttin each row in a variable $values
foreach ($values as $key=>$data) { //you're looping inside values taking the array index $key and the value inside that index $data
if ($key == 'id2') { //test if $key (index) is = to id2
print '<br>value: '.$value; // print the value inside that index
}
}
}
this is just an explanation, to what is going wrong with your code, but as #Pawel_W there is no need for the second foreach loop you can directly test
if($values['field']=='id2'){ print $values['value'];}
I think you just need to use array_search.
And here is recursive array_search ;
Assuming there might be multiple fields with the same name and you want them all as array, here's an alternative take:
array_filter(array_map(function($item) { return $item['field'] == 'id2' ? $item['value'] : null; }, $json['values']));
If your field names are always unique and you just want a single scalar:
array_reduce($json['values'], function($current, $item) { return $item['field'] == 'id2' ? $item['value'] : $current; });
(note that this one is not ideal since it will walk all the array even if match is found in first element)
And here's a gist with both in this and function form + output.

multi array usage in foreach loop

I've got the following array stored in a $_SESSION
[Bookings] => Array
(
[date] => Array
(
[0] => 1/12/2013
[1] => 1/19/2013
[2] => 2/03/2013
)
[price] => Array
(
[0] => 100
[1] => 150
[2] => 120
)
)
However I want to use a foreach loop and perform calculation on both values within the array.I can't seem to fugure out how I can use the foreach to accomodate multivalues, I've got a sample of a foreach I wrote below of what I'm trying to achieve. Anyone point me in the right direction.
foreach ($_SESSION['Bookings'] as $bookings)
{
myDate = $bookings[date];
myPrice = $bookings[price];
// Some other stuff here
}
foreach ($_SESSION['Bookings']['date'] as $key => $value) {
$myDate = $value;
$myPrice = $_SESSION['Bookings']['price'][$key];
}
simpler I guess :)
foreach (array_keys($_SESSION['Bookings']['date']) as $key)
{
$myDate = $_SESSION['Bookings']['date'][$key];
$myPrice = $_SESSION['Bookings']['price'][$key];
}
Should work?
Some info on: array_keys
just loop through on of your subarrays and read the corresponding value from the other
foreach ( $_SESSION['Bookings'][ 'date' ] as $key => $myDate) {
$myPrice = $_SESSION['Bookings'][ 'price' ][ $key ];
// here you can access to $myDate and $myPrice
// Some other stuff here
}

How to setup a PHP multidimensional array and declare the array keys?

I need some help setting up a PHP array. I get a little lost with multidimensional arrays.
Right now, I have an array with multiple products as follows:
If I do: print_r($products['1']); I get:
Array ( [0] => size:large [1] => color:blue [2] => material:cotton )
I can do print_r($products['2']); , etc and it will show a similar array as above.
I am trying to get it where I can do this:
echo $products['1']['color']; // the color of product 1
...and echo "blue";
I tried exploding the string and adding it to the array as follows:
$step_two = explode(":", $products['1']);
foreach( $step_two as $key => $value){
$products['1'][$key] = $value;
}
I know I'm obviously doing the explode / foreach way wrong but I wanted to post my code anyway. I hope this is enough information to help sort this out.
Try this:
foreach ($products as &$product)
{
foreach ($product as $key => $value)
{
list($attribute, $val) = explode(':',$value);
$product[$attribute] = $val;
// optional:
unset($product[$key]);
}
}
?>
Here goes a sample that will convert from your first form to your desired form (output goes below)
<?php
$a = array( '1' => array('color:blue','size:large','price:cheap'));
print_r($a);
foreach ($a as $key => $inner_array) {
foreach ($inner_array as $key2 => $attribute) {
$parts = explode(":",$attribute);
$a[$key][$parts[0]] = $parts[1];
//Optional, to remove the old values
unset($a[$key][$key2]);
}
}
print_r($a);
?>
root#xxx:/home/vinko/is# php a.php
Array
(
[1] => Array
(
[0] => color:blue
[1] => size:large
[2] => price:cheap
)
)
Array
(
[1] => Array
(
[color] => blue
[size] => large
[price] => cheap
)
)
You would be better of to build the array the right way, but to solve your problem you need to explode in the loop, something like:
foreach( $products['1'] as $value){
$step_two = explode(":", $value);
$products['1'][$step_two[0]] = $step_two[1];
}
You can wrap another foreach around it to loop over your whole $products array.
And you'd also better build a new array to avoid having both the old and the new values in your $products array.
You are right: you got the "foreach" and "explode" the wrong way around. Try something like this:
foreach($products['1'] as $param => $value) {
$kv = explode(":", $value);
if(count($kv) == 2) {
$products[$kv[0]] = $kv[1];
unset($products['1'][$param]);
}
}
This code first loops over the sub-elements of your first element, then splits each one by the colon and, if there are two parts, sets the key-value back into the array.
Note the unset line - it removes array elements like $products['1'][1] after setting products['1']['color'] to blue.
If you already have $products structured in that way, you can modifty its structure like this:
$products = array(
'1' => array(
0 => 'size:large', 1 => 'color:blue', 2 => 'material:cotton'
),
'2' => array(
0 => 'size:small', 1 => 'color:red', 2 => 'material:silk'
),
);
foreach ($products as &$product) {
$newArray = array();
foreach ($product as $item) {
list($key, $value) = explode(':', $item);
$newArray[$key] = $value;
}
$product = $newArray;
}
print_r($products);
If you don't want to overwrite original $products array, just append $newArray to another array.
<?php
$products = array();
$new_product = array();
$new_product['color'] = "blue";
$new_product['size'] = "large";
$new_product['material'] = "cotton";
$products[] = $new_product;
echo $products[0]['color'];
//print_r($products);

Getting values from associative array

I have the following main array called $m
Array
(
[0] => Array
(
[home] => Home
)
[1] => Array
(
[contact_us] => Contact Us
)
[2] => Array
(
[about_us] => About Us
)
[3] => Array
(
[feedback_form] => Feedback Form
)
[4] => Array
(
[enquiry_form] => Products
)
[5] => Array
(
[gallery] => Gallery
)
)
I have the values eg home, contact_us in a array stored $options , I need to get the values from the main array called $m using the $options array
eg. If the $options array has value home, i need to get the value Home from the main array ($m)
my code looks as follows
$c = 0;
foreach($options as $o){
echo $m[$c][$o];
++$c;
}
I somehow just can't receive the values from the main array?
I'd first transform $m to a simpler array with only one level:
$new_m = array();
foreach ($m as $item) {
foreach ($item as $key => $value) {
$new_m[$key] = $value;
}
}
Then you can use:
foreach ($options as $o) {
echo $new_m[$o];
}
Try this:
foreach($options as $o){
foreach($m as $check){
if(isset($check[$o])) echo $check[$o];
}
}
Although It would be better TO have the array filled with the only the pages and not a multidimensional array
Assuming keys in the sub arrays are unique you can
merge all sub arrays into a single array using call_user_func_array on array_merge
swap keys and values of your option array
Use array_intersect_key to retrieve an array with all the values.
Example like so:
$options = array('about_us', 'enquiry_form');
$values = array_intersect_key(
call_user_func_array('array_merge', $m), // Merge all subarrays
array_flip($options) // Make values in options keys
);
print_r($values);
which results in:
Array
(
[about_us] => About Us
[enquiry_form] => Products
)
How's this?
foreach( $options as $option )
{
foreach( $m as $m_key => $m_value )
{
if( $option == $m_key )
{
echo 'Name for ' . $options . ' is ' . $m_value;
break;
}
}
}
Try using a recursive array_walk function, for example
$a = array(
array('ooo'=>'yeah'),
array('bbb'=>'man')
);
function get_array_values($item, $key){
if(!is_numeric($key)){
echo "$item\n";
}
}
array_walk_recursive($a,'get_array_values');
Are you sure that the options array is in the same order of $m? Maybe you your
echo $m[$c][$o];
is resolving into a $m[0]['gallery'] which is obviously empty.
you can try different solutions, to me, a nice one (maybe not so efficient) should be like this:
for($c=0, $limit=count($c); $c < $limit; $c++)
if (array_search(key($m[$c]), $options))
echo current($m[$c]);
If you would like to use your approach have to flatten your array with something like this:
foreach ($m as $o)
$flattenedArray[key($o)]=current($o);
foreach ($options as $o)
echo $flattenedArray($o);
Doing this, though, eliminates duplicate voices of your original array if there are such duplicates.
$trails1 = array();
foreach ($trails as $item) {
foreach ($item as $key => $value) {
$trails1[].= $value;
}
}
echo '<pre>';print_r($trails1);
exit;

Categories