I've the following variable that is dinamically created:
$var = "'a'=>'123', 'b'=>'456'";
I use it to populate an array:
$array=array($var);
I can't do $array=array('a'=>'123', 'b'=>'456') because $var is always different.
So it shows me:
Array
(
[0] => 'a'=>'123', 'b'=>'456'
)
This is wrong, 'cause I need to get:
Array
(
[a] => 123
[b] => 456
)
What is wrong on my code?
Thanks in advance.
Ideally you should just leverage PHP's syntax to populate an associative array, something like this:
$array = [];
$array['a'] = '123';
$array['b'] = '456';
However, you could actually write a script which parses your input to generate an associate array:
$var = "'a'=>'123', 'b'=>'456'";
preg_match_all ("/'([^']+)'=>'([^']+)'/", $var, $matches);
$array = [];
for ($i=0; $i < count($matches[0]); $i++) {
$array[$matches[1][$i]] = $matches[2][$i];
}
print_r($array);
This prints:
Array
(
[a] => 123
[b] => 456
)
Related
I have an existing array in this following structure,
Array
(
[0] => 1
[1] => 3
)
And, I want to convert in the following structure:
Array
(
[0] => Array
(
[class_id] => 1
)
[1] => Array
(
[class_id] => 3
)
)
Any suggestions, please let me know.
Thanks in advance!
Use a map to iterate over the array items and return a new array for each one of them.
<?php
function map($n) {
return [
'class_id' => $n
];
}
$a = array(1, 3);
$b = array_map("map", $a);
print_r($b);
?>
U just need to foreach this like this:
$data = [1, 3];
$result = [];
foreach ($data as $item) {
$result[] = ["class_id" => $item];
}
Seems that is exactly u need )
One liner:
array_walk($data, function(&$n){ $n = ['class_id'=>$n]; })
Keep in mind that we:
Pass the array as a reference to array_walk.
Then we pass each element as a reference to modify its content.
Also, array_walk keeps your index intact.
I would like to change values in an array. Here is my starting array:
Array
(
[0] => Array
(
[name] => aaa
)
[1] => Array
(
[name] => bbb
)
[2] => Array
(
[name] => ccc
)
)
I declare a searchterm (eg. "aaa") and a new name for it (eg. "test"). And than I do a str_replace to actually change it.
Unfortunately nothing changes nor do I get an error message. Can you please help and tell me where my error is please?
for ($i=0; $i < count($json) ; $i++) {
$search = $old_name;
$replace = $new_name;
str_replace($search, $replace, $json[$i]['name']);
print_r($json);
}
As the documentation says, this function doesn't update the array
This function returns a string or an array with the replaced values.
you need to update it with the returned value:
for ($i=0; $i < count($json) ; $i++) {
$search = $old_name;
$replace = $new_name;
$json[$i]['name'] = str_replace($search, $replace, $json[$i]['name']);
print_r($json);
}
str_replace returns a string. I think you are trying to use it as though it alters a parameter that was passed by reference. Instead you should assign the returned value to the array at the correct index.
for ($i=0; $i < count($json) ; $i++) {
$search = $old_name;
$replace = $new_name;
$json[$i]['name'] = str_replace($search, $replace, $json[$i]['name']);
print_r($json);
}
If you want to replace/change more than one name, I suggest you to use the below code.
// define an array with keys as new name and value as old name ( name to be replaced).
$change_name_array= array('test'=>'aaa','another_test'=>'bbb');
// loop the array
for ($i=0; $i < count($json) ; $i++) {
// check if the name is in defined array
if(in_array($json[$i]['name'],$change_name_array)){
// get the key and replace it.
$json[$i]['name'] = array_search($json[$i]['name'], $change_name_array);
}
}
Out put: here aaa id replaced with test and bbb is replaced with another_test
Array
(
[0] => Array
(
[name] => test
)
[1] => Array
(
[name] => another_test
)
[2] => Array
(
[name] => ccc
)
)
I have a little problem. Here is the code:
$arr = explode(',', $odluka);
$arr2 = array($arr[0], $arr[1], $arr[2], $arr[3], $arr[4], $arr[5], $arr[6], $arr[7], $arr[8], $arr[9]);
while ($arrk = current($arr2)) {
if ($arrk == '1') {
$ark = key($arr2);
//print_r($ark);
//echo $arr2[$ark];
$arop = explode(',', $utroseno);
$aropk = array($arop[0], $arop[1], $arop[2], $arop[3], $arop[4], $arop[5], $arop[6], $arop[7], $arop[8], $arop[9]);
$array = array($aropk[$ark]);
print_r($array);
}
next($arr2);
}
Output of $array is
Array ( [0] => 1 ) Array ( [0] => 5 ) Array ( [0] => 10 ) Array ( [0] => 4 ) Array ( [0] => 4 ) Array ( [0] => 1 ) Array ( [0] => 1 )
How can I merge this values and sum them. I want sum of 1+5+10+4+4+1+1. Thanks!
declare a variable to store sum
iterate over array
-> add value to sum
Here is a simple example how to deal with your output array:
$data = [
[1], [5], [10], [4]
];
$sum = array_sum(array_map(function($elem) { return $elem[0]; }, $data));
var_dump($sum);
You don't need to assign them to another array and loop..you can just sum everything after explode. You just need one line of code for that:
array_sum(explode(',', $odluka));
Then you'll get the sum of all the numbers
Not need using any array and loop.You are using only "array_sum ()" php building function.Like
<?php
$foo[] = "12";
$foo[] = 10;
$foo[] = "bar";
$foo[] = "summer";
echo array_sum ($foo); //same as echo "22";
?>
For more information Read Php Manual link
Use this function
array_sum ($arr);
I have two arrays $t1 and $t2. When I print them out I get the following:
t1:
Array ( [0] => Christina Aguilera [1] => Iron Maiden [2] => Bob Marley )
t2:
Array ( [0] => Bob Marley )
I'm trying to get the common elements of the array though the array_intersect function, and I'm using the below line:
$intersection = array_intersect($t1,$t2);
However, for some reason when I print the result $intersection I get get:
Array ( )
Can anybody see what it is going wrong? The code for my function is below but I think the above should be sufficient to work it out.
// For extra information
function findMutualInterests($_uProArray, $_tProArray)
{
$_commonDetails = null;
$_fieldNames = array_keys($_uProArray[0]);
$_uProValues = array_values($_uProArray[0]);
$_tProValues = array_values($_tProArray[0]);
//print_r($_uProValues);
// Iterate over the arrays and find ones in common
for ($i = 0; $i < count($_uProValues); $i++) {
$t1 = explode(',',$_uProValues[$i]);
print_r($t1);
$t2 = explode(',',$_tProValues[$i]);
print_r($t2);
$intersection = array_intersect($t1,$t2);
print_r($intersection);
$_commonDetails[$_fieldNames[$i]] = implode($intersection);
}
return $_commonDetails;
}
EDIT: Just thought I would point out that the output of $t1 and $t2 shown above are the output of a single iteration of the below function. I just chose that one as an example.
Your code works fine, try trimming input strings.
Your code has a huge mistake.
If you have more elements in $_tProValues than in $_uProValues you will not test all possibilities in the $_tProValues array. Then you'll not be able to test all possibilities. What happens here is exactly that, you're not testing all possibilities.
Check the comments above, because this works just fine:
<?php
$a = array (
0 => 'Christina Aguilera',
1 => 'Iron Maiden',
2 => 'Bob Marley'
);
$b = array (
0 => 'Bob Marley'
);
$intersect = array_intersect( $a, $b );
print_r( $intersect );
?>
Output:
Array
(
[2] => Bob Marley
)
**Check the code it is very useful for you ,because this works fine:**
$final_arr = [];
foreach ($a as $a_val) {
foreach ($b as $b_val) {
if(in_array(strtolower($a), array_map('strtolower', $b_val))){
$final_arr[] = $b_val;
}
}
}
I have two variables, which are both arrays:
$var1=array();
$var1['something']['secondary_something'][1]="foo";
$var1['something']['secondary_something'][2]="foo";
$var1['something']['secondary_something'][3]="foo";
$var1['something']['secondary_something'][4]="foo";
Now I have a function, that takes an array for input:
function something($input=array()){
print_r($input);//print the array out
}//end of function
But I need $input to be like a reference to $var1, so when I call the function, appending to variable 2 ($input) like this:
$myInputVar=array();
$myInputVar['something']['secondary_something'][]="foo";
$myInputVar['something']['secondary_something'][]="foo";
//Notice how I append to the var above, not giving a key name in the third dimension of the array.
something($myInputVar);
Now that would simply print:
Array ( [something] => Array ( [secondary_something] => Array ( [0] => foo [1] => foo ) ) )
But I need the second var ($input, from the function) to be a reference of the first var ($var1).
So, the end result should be:
Array ( [something] => Array ( [secondary_something] => Array ( [5] => foo [6] => foo ) ) )
Some guys have told me to use the =& (which makes one var a reference to another), but I just can't seem to get my head around how I would do it with =& in this case.
Is what I'm trying to do even possible? If so, could you please shine some light on it.
I am struggling to understand what you are trying to achieve.
Why would you print the array out?
You always need a value and an array if you want to push something into the array.
You can do this with
function something(&$array, $val) { // take the assigned $array as reference
$array[] = $val;
}
Then calling with
$test = array();
something($test, 'foo');
print_r($test); // => array ( 'test' )
I hope this helps
EDIT
function something(&$array, $array_new) {
$array = array_merge($array, $array_new); // to combine/merge both arrays
// please keep in mind that $array is technically $var, because it references to this variable
}
$var1=array();
$var1['something']['secondary_something'][1]="foo";
$var1['something']['secondary_something'][2]="foo";
$var1['something']['secondary_something'][3]="foo";
$var1['something']['secondary_something'][4]="foo";
$myInputVar=array();
$myInputVar['something']['secondary_something'][]="foo";
$myInputVar['something']['secondary_something'][]="foo";
something($var, $myInputVar);
You can make the function receive a reference to the array. Like so:
function something(&$arr) {
$arr['something']['secondary_something'][]="something1";
$arr['something']['secondary_something'][]="something2";
}
Now you can do something like the following:
$var1 = array();
$var1['something']['secondary_something'][1]="foo";
$var1['something']['secondary_something'][2]="bar";
$var1['something']['secondary_something'][3]="foobar";
$var1['something']['secondary_something'][4]="barfoo";
something($var1); //this should now append the items to $var1.
print_r($var1); //check to see if calling 'something' really did add the items.
Try this:
$var1 = array();
$var2 = array();
assign($var1, $var2, 'foo'); // add an item in both $var1 & $var2
assign($var1, $var2, 'bar'); // append another item it both $var1 & $var2
assign($var1, $var2, 'buz', 5); // add an item in both $var1 & $var2 at index 5
echo print_r($var1, TRUE) . print_r($var2, TRUE);
function assign(&$var1, &$var2, $value, $index=NULL) {
if (is_int($index)) {
$var1['something']['secondary_something'][$index] = $var2['something']['secondary_something'][$index] = $value;
} else {
$var1['something']['secondary_something'][] = $var2['something']['secondary_something'][] = $value;
}
}
which will output:
Array ( [something] => Array ( [secondary_something] => Array ( [0] => foo [1] => bar [5] => buz ) ) ) Array ( [something] => Array ( [secondary_something] => Array ( [0] => foo [1] => bar [5] => buz ) ) )