I have the following:
$values = Array (
['level1'] => Array (
['level2'] => Array(
['level3'] => 'Value'
)
)
)
I also have an array of keys:
$keys = Array (
[0] => 'level1',
[1] => 'level2',
[2] => 'level3'
)
I want to be able to use the $keys array so I can come up with: $values['level1']['level2']['level3']. The number of levels and key names will change so I need a solution that will read my $keys array and then loop through $values until I get the end value.
You could iterate over $values and store a $ref like this :
$ref = $values ;
foreach ($keys as $key) {
if (isset($ref[$key])) {
$ref = $ref[$key];
}
}
echo $ref ; // Value
You also could use references (&) to avoid copy of arrays :
$ref = &$values ;
foreach ($keys as &$key) {
if (isset($ref[$key])) {
$ref = &$ref[$key];
}
}
echo $ref ;
<?php
$values['level1']['level2']['level3'] = 'Value';
$keys = array (
0 => 'level1',
1 => 'level2',
2 => 'level3'
);
$vtemp = $values;
foreach ($keys as $key) {
try {
$vtemp = $vtemp[$key];
print_r($vtemp);
print("<br/>---<br/>");
}
catch (Exception $e) {
print("Exception $e");
}
}
Hope this helps. Of course remove the print statements but I tried it and in the end it reaches the value. Until it reaches the values it keeps hitting arrays, one level deeper at a time.
Related
I'm having an array key-value pair. I need to create new array from this key and value pair. for eg
I tried with foreach loop
foreach($array as $key => $val){
// here i m getting key and value i want to combine key and value in single array
}
Array
(
'146' => Array
(
'sam' => Array (
'dex',
'max'
)
)
'143' => Array
(
'tim' => Array (
'thai',
'josh'
)
)
)
and the expected output is push key as first element
$out = [
[ 'sam', 'dex', 'max'],
[ 'tim','thai', 'josh']
];
You can use array-merge as:
foreach($array as $key => $val)
$out[] = array_merge([$key], $val);
Notice that in your example you also have another level of keys ("146", "143") -> you need to remove it before using this code.
Edited:
foreach($arr as $val) {
$key = key($val);
$out[] = array_merge([$key], $val[$key]);
}
Live example: 3v4l
What about this?
$output = [];
foreach($array as $key => $val) {
$data = $val;
array_unshift($data, $key);
$output[] = $data;
}
So, we need to flatten the array for each key in your array.
We make a function which recursively calls the further deep arrays and we collect all these results in a new array which is passed as a second parameter.
Code:
<?php
$arr = Array(
'146' => Array
(
'sam' => Array (
'dex',
'max'
)
),
'143' => Array
(
'tim' => Array (
'thai',
'josh'
)
)
);
$result = [];
foreach($arr as $key => $value){
$flat_data = [];
flattenArray($value,$flat_data);
$result[] = $flat_data;
}
function flattenArray($data,&$flat_data){
foreach ($data as $key => $value) {
if(is_array($value)){
$flat_data[] = $key;
flattenArray($value,$flat_data);
}else{
$flat_data[] = $value;
}
}
}
print_r($result);
Demo: https://3v4l.org/bX9R3
Since, we are passing a new array to collect the results as second parameter, this would perform better than returning an array of results on each function call and then doing an array merge(which would have made a bit inefficient).
This would work independent of the depth of levels.
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); }
}
I have an generated array into this format and want to generated a second array to fit into a file that expects the specific format
This is the array i have :
(int) 0 => array(
[Service] => Array
(
[id] => 6948229
[document] => Array
(
[number] => 0003928425
)
)
This is the array i want to build from the previous array (will have many indexes)
verified[id]
verified[number]
So far i build this script:
foreach($data as $key=>$value )
{
echo '<br>key '.$key;
foreach($value as $k=>$v)
{
$Verified[$key]['id'] = $v["id"];
$Verified[$key]['number'] = $v['document']['number'];
But just get undefined index error message.
Which indexes i must use to get the flatten array ?
From what I can make from your question, you can do something like this to get the desired output,
$Verified = []; //use array() for versions below 5.5
foreach($data as $key=>$value )
{
echo '<br>key '.$key;
foreach($value as $k=>$v)
{
if(is_array($v)){
$Verified[$key]['number'] = $v['document']['number'];
}
$Verified[$key]['id'] = $v['id'];
Please pass your array to this function
function arrayconvert($arr) {
if (is_array($arr)) {
foreach($arr as $k => $v) {
if (is_array($v)) {
arrayconvert($v);
} else {
$newarr[$k] = $v;
}
}
}
return $newarr;
}
There is no need of second foreach and you are getting undefined index because you are using $v['id'] insted of $val['id'] in that line $Verified[$key]['id'] = $v["id"];
<?php
$data = array('Service' => array('id' => 6948229,'document' => array ('number' => '0003928425' )));
$verified = array();
foreach($data as $key => $val)
{
$verified[$key]['id'] = $val['id'];
$verified[$key]['number'] = $val['document']['number'];
}
echo "<pre>"; print_r($verified);
?>
output
Array
(
[Service] => Array
(
[id] => 6948229
[number] => 0003928425
)
)
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);
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;