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

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

Related

PHP array with foreach

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

Convert Indexed Array to Associate Array with Indexed Exploded Values

Having issues converting an array like this into an associative array
$array =
Array
(
[0] => 154654654455|WS01
[1] => 456541232132|WS02
)
Into an associative array.
I can do a foreach loop and explode the values
$values2 = array();
foreach ($array as $key => $value) {
$values2[] = explode("|",$value);
}
But then I get something like this
Array
(
[0] => Array
(
[0] => 154654654455
[1] => WS01
)
[1] => Array
(
[0] => 456541232132
[1] => WS02
)
)
What's the best way to convert something like this into an associative array like such
Array
(
[154654654455] => WS01
[456541232132] => WS02
)
$values2 = array();
foreach ($array as $key => $value) {
$expl = explode("|",$value);
$values2[$expl[0]] = $expl[1];
}
Probably not the most elegant way, but modifying your approach it would be:
$values2 = array();
foreach ($array as $key => $value) {
$t = explode("|",$value);
$values2[$t[0]] = $t[1];
}
change your foreach loop to this
foreach ($array as $key => $value) {
$temp = explode("|",$value);
$values2[$temp[0]] = $temp[1];
}
All you need to do is to set the the first item of the explode as key and the second as value:
$array = [
'154654654455|WS01',
'456541232132|WS02',
];
$values2 = [];
foreach ($array as $key => $value) {
$data = explode('|', $value);
$values2[$data[0]] = $data[1];
}
Demo: https://3v4l.org/cEJE5
Not the best answer, but for completeness; after your loop you can extract the 1 column as values and index on the 0 column:
$values2 = array_column($values2, 1, 0);
I am going to put the exact same answer here as everyone else,but I will omit the unused $key variable...
$val2 = array();
foreach ($array as $v) {
$tmp = explode("|",$v);
$val2[$tmp[0]] = $tmp[1];
}

Get only Numeric values from Array in PHP

I have an array that looks something like this:
Array (
[0] => Array ( [country_percentage] => 5 %North America )
[1] => Array ( [country_percentage] => 0 %Latin America )
)
I want only numeric values from above array. I want my final array like this
Array (
[0] => Array ( [country_percentage] => 5)
[1] => Array ( [country_percentage] => 0)
)
How I achieve this using PHP?? Thanks in advance...
When the number is in first position you can int cast it like so:
$newArray = [];
foreach($array => $value) {
$newArray[] = (int)$value;
}
I guess you can loop the 2 dimensional array and use a preg_replace, i.e.:
for($i=0; $i < count($arrays); $i++){
$arrays[$i]['country_percentage'] = preg_replace( '/[^\d]/', '', $arrays[$i]['country_percentage'] );
}
Ideone Demo
Update Based on your comment:
for($i=0; $i < count($arrays); $i++){
if( preg_match( '/North America/', $arrays[$i]['country_percentage'] )){
echo preg_replace( '/[^\d]/', '', $arrays[$i]['country_percentage'] );
}
}
Try this:
$arr = array(array('country_percentage' => '5 %North America'),array("country_percentage"=>"0 %Latin America"));
$result = array();
foreach($arr as $array) {
$int = filter_var($array['country_percentage'], FILTER_SANITIZE_NUMBER_INT);
$result[] = array('country_percentage' => $int);
}
Try this one:-
$arr =[['country_percentage' => '5 %North America'],
['country_percentage' => '0 %Latin America']];
$res = [];
foreach ($arr as $key => $val) {
$res[]['country_percentage'] = (int)$val['country_percentage'];
}
echo '<pre>'; print_r($res);
output:-
Array
(
[0] => Array
(
[country_percentage] => 5
)
[1] => Array
(
[country_percentage] => 0
)
)
You can use array_walk_recursive to do away with the loop,
passing the first parameter of the callback as a reference to modify the initial array value.
Then just apply either filter_var or intval as already mentioned the other answers.
$array = [
["country_percentage" => "5 %North America"],
["country_percentage" => "0 %Latin America"]
];
array_walk_recursive($array, function(&$value,$key){
$value = filter_var($value,FILTER_SANITIZE_NUMBER_INT);
// or
$value = intval($value);
});
print_r($array);
Will output
Array
(
[0] => Array
(
[country_percentage] => 5
)
[1] => Array
(
[country_percentage] => 0
)
)
You could get all nemeric values by looping through the array. However I don't think this is the most efficient and good looking answer, I'll post it anyways.
// Array to hold just the numbers
$newArray = array();
// Loop through array
foreach ($array as $key => $value) {
// Check if the value is numeric
if (is_numeric($value)) {
$newArray[$key] = $value;
}
}
I missunderstood your question.
$newArray = array();
foreach ($array as $key => $value) {
foreach ($value as $subkey => $subvalue) {
$subvalue = trim(current(explode('%', $subvalue)));
$newArray[$key] = array($subkey => $subvalue);
}
}
If you want all but numeric values :
$array[] = array("country_percentage"=>"5 %North America");
$array[] = array("country_percentage"=>"3 %Latin America");
$newArray = [];
foreach ($array as $arr){
foreach($arr as $key1=>$arr1) {
$newArray[][$key1] = intval($arr1);
}
}
echo "<pre>";
print_R($newArray);
This is kind of a ghetto method to doing it cause I love using not as many pre made functions as possible. But this should work for you :D
$array = array('jack', 2, 5, 'gday!');
$new = array();
foreach ($array as $item) {
// IF Is numeric (each item from the array) will insert into new array called $new.
if (is_numeric($item)) { array_push($new, $item); }
}

PHP; Iterate through an assoc. array and add together all values

I have an array that I need to 'merge' the values of, and then flatten the entire thing to not be associative. I have this working, but I was hoping to find a better way.
Here's, in essence, the array:
array (
[label] => array(
[0] => array(
key => val
)
[1] => array(
key => val
)
)
[label2] => array(
[0] => array(
key => val
)
)
What I do with this is to add all values from [0] and [1] per assoc. array and return 1 array, where the output is something like:
array (
[label] => array(
[0] => array(
key => SUM(val1+val2)
)
)
[label2] => array(
[0] => array(
key => val
)
)
I do this by:
$i = array();
foreach ($array AS $key => $val) {
$i[$key] = NULL;
foreach ($val AS $r) foreach ($r AS $k => $v) {
if (count($array[$key]) > 1) { // Add value.
$i[$key][$k] += $v;
} else { // Leave alone.
$i[$key][$k] = $v;
}
}
}
Then I flatten it into one big array by using:
$array = array();
$r = new RecursiveIteratorIterator(
new RecursiveArrayIterator($array)
);
foreach ($r as $key => $val)
$array[$key] = $val;
return $array
I think this is ugly and could be done in a much more efficient way. I just can't figure it out, and SPL confuses me; but I want to learn.
Can someone help?
I think I figured it out:
$data = array();
$RII = new RecursiveIteratorIterator(
new RecursiveArrayIterator($it)
);
foreach($RII AS $key => $val) {
$data[$RII->key()] += $RII->current();
}
$this->fullData = $data;
Did everything I needed to in less code. Does this look right?
$data = array();
$RII = new RecursiveIteratorIterator(
new RecursiveArrayIterator($it)
);
foreach($RII AS $key => $val) {
$data[$RII->key()] += $RII->current();
}
$this->fullData = $data;
Replaces both functions above. It goes through the multidimensional array without question and allows me to do what I needed to do.

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