I have an array like
$array = Manufacturer => BMW
Miles => 10000
and I would like to use this to create a new array with a specific name/value like this :
$array = st_selval_0_0 => Manufacturer
st_tmdata_0_0 => BMW
st_selval_0_1 => Miles
st_tmdata_0_1 => 10000
As you can see the last digit must increase on each new name=>value.
$result = array();
$i = 0;
foreach($array as $key => $val) {
$result['st_selval_0_'.$i] = $key;
$result['st_tmdata_0_'.$i] = $val;
$i++;
}
See also foreach in the manual.
$newArray = array();
$i=0;
foreach($array as $k => $v)
{
$newArray["st_selval_0_$i"] = $k;
$newArray["st_tmdata_0_$i"] = $v;
$i++;
}
$input = array('Manufacturer' => 'BMW', 'Miles' => 10000);
$output = array();
$i = 0;
foreach ($input as $key => $value) {
$output['st_selval_0_' . $i] = $key;
$output['st_tmdata_0_' . $i] = $value;
$i++;
}
print_r($output);
Output:
Array
(
[st_selval_0_0] => Manufacturer
[st_tmdata_0_0] => BMW
[st_selval_0_1] => Miles
[st_tmdata_0_1] => 10000
)
Related
Array
(
[0] => Array( [0] => Array( [value] => 25 ) )
[1] => Array( [0] => Array( [value] => 75 ) )
[2] => Array( [0] => Array( [value] => 10 ) )
[3] => Array( [0] => Array( [value] => 10 ) )
)
I am working on a custom module in drupal and need to sum up the [value],
However I tried different approaches using array_column, array_sum, but didn't get the solution.
Any help would be appreciated. Thanks.
Code
$contributionDetails = $node->get('field_contributions')->getValue();
foreach ( $contributionDetails as $element ) {
$p = Paragraph::load( $element['target_id'] );
$text[] = $p->field_contribution_percentage->getValue();
}
You could make use of array_map here instead of an accumulator:
$arraySum = array_map(function ($v) {
return reset($v)['value'];
}, $text);
print_r(array_sum($arraySum)); // 120
Edit, as a full example:
$values = [
[['value' => 25]],
[['value' => 75]],
[['value' => 10]],
[['value' => 10]],
];
echo array_sum(array_map(function ($v) {
return reset($v)['value'];
}, $values)); // 120
A couple of loops and an accumulator is one way to achieve this
$tot = 0;
foreach ($array as $a){
foreach ($a as $b){
$tot += $b['value'];
}
}
echo $tot;
Or if you are sure there will always only be one occurance of the inner array.
$tot = 0;
foreach ($array as $a){
$tot += $a[0]['value'];
}
echo $tot;
Or using the code you just posted
$contributionDetails = $node->get('field_contributions')->getValue();
$tot = 0;
foreach ( $contributionDetails as $element ) {
$p = Paragraph::load( $element['target_id'] );
$text[] = $p->field_contribution_percentage->getValue();
$tot += $p->field_contribution_percentage->getValue();
}
echo $tot;
So you have an array containing 2 arrays which have the index 'value', you just need to loop each array using nested foreach and a variable $sum which sum up the value on each iteration.
Try this code:
<?php
$sum = 0;
foreach($array as $value) {
foreach ($value as $v){
$sum += $v['value'];
}
}
echo $sum;
This will output 120
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];
}
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); }
}
Going through foreach loop for filter on my site I get array back like this:
Array
(
[21] => Blau
[24] => Azul
[28] => Blue
)
By choosing next filter another array will be created:
Array
(
[21] => Grün
[24] => Verde
[28] => Green
)
and so on...
What I what to do is merge values of these arrays on same keys. So it have to be look like this:
Array
(
[21] => Blau-Grün
[24] => Azul-Verde
[28] => Blue-Green
)
It worked with Uchiha's code. I made some changed inside my loop:
foreach (...){
//some logic before
$array[] = array();
$i = 0;
foreach($array as $k => $v){
$i++;
foreach($array[$k] as $key => $value){
if(array_key_exists($key, $array[$i])){
$result[$key] = $value . '-' . $array[$i][$key];
}
}
}
echo '<pre>' . print_r($result,true) . '</pre>';
}
$maxItems = max(count($blue),count($green));
for ($i = 0; $i < $maxItems; $i++) {
if (isset($blue[$i], $green[$i])) {
$combined[$i] = $blue[$i].'-'.$green[$i];
} else {
if (isset($blue[$i])) {
$combined[$i] = $blue[$i];
} else {
$combined[$i] = $green[$i];
}
}
}
You can use foreach along with array_key_exists as
foreach($arr1 as $key => $value){
if(array_key_exists($key, $arr2)){
$result[$key] = $value.'-'.$arr2[$key];
}
}
Fiddle
you can use array_map with a closure that joins the two values, e.g.
$joined = array_map(function($m, $n){ return $m . '-' . $n; }, $array1, $array2);
$foo = array(1 => "Bob", 2 => "Sepi");
$bar = array(1 => "sach", 2 => "john");
$foobar= array();
foreach ($foo as $key => $value) {
foreach ($bar as $key1 => $value1) {
if($key == $key1){
$foobar[] = $value."-".$value1;
}
}}
You can create a function, which takes both of arrays as parameter and identify which one has more elements, loop through and concat the string from another array at the same key.
$array1 = array(
'Blau',
'Azul',
'Blue'
);
$array2 = array(
'Grün',
'Verde',
'Green'
)
function mergeArray($array1, $array2){
$newArray = array();
if(count($array1) >= count($array2)){
foreach($array1 as $key => $value){
$newArray[] = $value . (array_key_exists($key, $array2) ? '-' . $array2[$key] : '');
}
} else {
foreach($array2 as $key => $value){
$newArray[] = $value . (array_key_exists($key, $array1) ? '-' . $array1[$key] : '');
}
}
}
$newArray = mergeArray($array1, $array2);
$newArray contains the result you expected.
here is simple and tested code
<?php
$a1=array(
1 => 'Blau',
2 => 'Azul',
3 => 'Blue'
);
$a2=array
(
1 => 'Grün',
2 => 'Verde',
4 => 'Green'
);
$a3=$a1 + $a2;
$a4=$a2 + $a1;
foreach($a3 as $key=>$val){
if($a4[$key] != $a3[$key]){
$a3[$key] = $a3[$key].' '.$a4[$key];
}
}
print_r($a3);
?>
i have arrays like this
Array(
[0] => Array(
[member_name] => hohoho
[member_type] => SUPPLIER
[interest] => Array(
[0] => HOLIDAY
[1] => MOVIES)
),
[1] => Array(
[member_name] => jajaja
[member_validity] => 13/12/2001
[interest] => Array(
[0] => SPORTS
[1] => FOODS)
)
)
how can I put the array keys and items in a separate variable? for example, i want to have something like
$keyholder[0] = member_name,member_type,interest
$keyholder[1] = member_name,member_validity,interest
$itemholder[0] = hohoho,SUPPLIER,{HOLIDAY,MOVIES}
$itemholder[1] = jajaja,13/12/2001,{SPORTS,FOODS}
Try array_keys() and array_values()
http://php.net/manual/en/function.array-keys.php
http://www.php.net/manual/en/function.array-values.php
You can cycle through an array and get the key and values like this:
foreach ($array as $key => $val)
{
echo $key." - ".$val."<br/>";
}
$keyholder=array();
$itemholder=array();
foreach($original_array as $values){
$inner_keys=array();
$inner_values=array();
foreach($values as $key=>$value){
$inner_keys[]=$key;
$inner_values[]=$value;
}
$keyholder[]=$inner_keys;
$itemholder[]=$inner_values;
}
I think this will do it:
$cnt = count($original);
$keys = array();
$items = array();
for($i = 0; $i < $cnt; $i++) {
$keys[] = array_keys($original[$i]);
$items[] = array_values($original[$i]);
}