Create associative array from Foreach Loop PHP - php

I have this foreach loop:
foreach($aMbs as $aMemb){
$ignoreArray = array(1,3);
if (!in_array($aMemb['ID'],$ignoreArray)){
$aMemberships[] = array($aMemb['ID'] => $aMemb['Name']);
}
}
This prints out the right fields but they are arrays inside arrays. I need the foreach loop to output a simple array like this one:
$aMemberships = array('1' => 'Standard', '2' => 'Silver');
What am I doing wrong?

You need to change your $aMemberships assignment
$aMemberships[] = $aMemb['Name'];
If you want an array
$aMemberships[$aMemb['ID']] = $aMemb['Name'];
if you want a map.
What you are doing is appending an array to an array.

Associative array in foreach statement:
foreach($nodeids as $field => $value) {
$field_data[$field]=$value;
}
Output:
Array(
$field => $value,
$field => $value
...
);
insertion in CodeIgniter:
$res=$this->db->insert($bundle_table,$field_data);

Instead of
$aMemberships[] = array($aMemb['ID'] => $aMemb['Name']);
Try
$aMemberships[$aMemb['ID']] = $aMemb['Name'];

Your existing code uses incremental key and uses the array as corresponding value.
To make make $aMemberships an associative array with key as $aMemb['ID'] and value being $aMemb['Name'] you need to change
$aMemberships[] = array($aMemb['ID'] => $aMemb['Name']);
in the foreach loop to:
$aMemberships[$aMemb['ID']] = $aMemb['Name']);

it prints an array of arrays because you are doing so in this line
$aMemberships[] = array($aMemb['ID'] => $aMemb['Name']);
where you [] after a variable your are indicating to assign the value in a new row of the array and you are inserting an other array into that row
so you can use the the examples the others haver already gave or you can use this method:
int array_push ( array &$array , mixed $var [, mixed $... ] )
here is an example that you can find in the api
<?php
$stack = array(0=>"orange",1=>"banana");
array_push($stack, 2=>"apple",3=>"raspberry");
print_r($stack);
?>
//prints
Array
(
[0] => orange
[1] => banana
[2] => apple
[3] => raspberry
)
http://php.net/manual/en/function.array-push.php

You get key and value of an associative array in foreach loop and create an associative with key and value pairs.
$aMemberships=array();//define array
foreach($aMbs as $key=>$value){
$ignoreArray = array(1,3);
if (!in_array($key,$ignoreArray)){
$aMemberships[$key] = $value;
}
}
It will give you an expected output:
array('1' => 'Standard', '2' => 'Silver');

Related

Return key values from first array whose key is in second array

I have two arrays I want to search from first array by key only which i have in second array and as third array i want to print result:
$colldata=array("bench-press-rod"=>'',"adidas-classic-backpack"=>'93549559913',"adidas-classic-backpack-legend-ink-multicolour"=>'',"puma-suede-classic-regal"=>'93549920361,93549723753');
$colldata2=array(0 => 'bench-press-rod',1 => 'adidas-classic-backpack');
Expected result:
array('bench-press-rod'=>'',"adidas-classic-backpack"=>'93549559913');
You can do this in one line in PHP, using array_flip to swap the keys and values of the second array, and then array_intersect_key to merge the two arrays on matching keys:
$colldata=array("bench-press-rod"=>'',"adidas-classic-backpack"=>'93549559913',"adidas-classic-backpack-legend-ink-multicolour"=>'',"puma-suede-classic-regal"=>'93549920361,93549723753');
$colldata2=array(0 => 'bench-press-rod',1 => 'adidas-classic-backpack');
print_r(array_intersect_key($colldata, array_flip($colldata2)));
Output:
Array
(
[bench-press-rod] =>
[adidas-classic-backpack] => 93549559913
)
Demo on 3v4l.org
About the simplest I can come up with is to loop through the second array and add the matching key from the first array into the output. If the item isn't present then it puts Not found in the output...
$output = [];
foreach ( $colldata2 as $item ) {
$output[$item] = $colldata[$item] ?? 'Not found';
}
print_r($output);
gives..
Array
(
[bench-press-rod] =>
[adidas-classic-backpack] => 93549559913
)
Check this.
$colldata=array("bench-press-rod"=>'',"adidas-classic-backpack"=>'93549559913',"adidas-classic-backpack-legend-ink-multicolour"=>'',"puma-suede-classic-regal"=>'93549920361,93549723753');
$colldata2=array(0 => 'bench-press-rod',1 => 'adidas-classic-backpack');
$result = [];
foreach ($colldata2 as $key => $value) {
if (array_key_exists($value, $colldata)) {
array_push($result,$colldata[$value]);
}
}
echo '<pre/>';
print_r($result);

Flatten 2d array and cast all string values to int

How should I make this array value that is in string form
Array
(
[0] => ["1","2"]
[1] => ["5"]
)
into int form
Array
(
[0] => 1
[1] => 2
[2] => 5
)
Is it complicated? Anyone can help?
you can use array_map to parse string to int and array_reduce with array_merge to join the arrays
$data = Array(["1","2"],["5"]);
$result = array_map('intval', array_reduce($data, 'array_merge', array()));
print_r($result);
Try this:
$array = [
["1", "2"],
["5"],
];
$newArray = [];
foreach ($array as $rowArr) {
foreach ($rowArr as $str) {
$newArray[] = intval($str);
}
}
var_dump($newArray);
This returns:
array (size=3)
0 => int 1
1 => int 2
2 => int 5
This works by iterating $array, then iterating $array's child elements ($rowArr) and adding each element to $newArray after running intval on it.
Use array_reduce (https://3v4l.org/H4eIV)
$a = Array
(
0=> ["1","2"],
1=> ["5"]
);
$r = array_reduce($a, 'array_merge', array());
var_export($r);
Result:
array (
0 => '1',
1 => '2',
2 => '5',
)
You only need to loop through the two layers of your array.
$input=[["1","2"],["5"]];
foreach($input as $a){
foreach($a as $v){
$result[]=+$v; // make integer
}
}
var_export($result);
Another way: create a closure that casts variables to ints and appends them to an array.
$appendInt = function($x) use (&$result) { $result[] = (int) $x; };
// reference to result array^ append to result^ ^cast to int
Apply it to every element of your multidimensional array with array_walk_recursive.
array_walk_recursive($your_array, $appendInt);
The flat array of ints will be in the $result variable.

php create multidimensional array from flat one

I have an array like this:
<?php
$array = array( 0 => 'foo', 1 => 'bar', ..., x => 'foobar' );
?>
What is the fastest way to create a multidimensional array out of this, where every value is another level?
So I get:
array (size=1)
'foo' =>
array (size=1)
'bar' =>
...
array (size=1)
'x' =>
array (size=1)
0 => string 'foobar' (length=6)
<?php
$i = count($array)-1;
$lasta = array($array[$i]);
$i--;
while ($i>=0)
{
$a = array();
$a[$array[$i]] = $lasta;
$lasta = $a;
$i--;
}
?>
$a is the output.
What exactly are you trying to do? So many arrays of size 1 seems a bit silly.
you probably want to use foreach loop(s) with a key=>value pair
foreach ($array as $k=>$v) {
print "key: $k value: $v";
}
You could do something like this to achieve the array you asked for:
$newArray = array();
for ($i=count($array)-1; $i>=0; $i--) {
$newArray = array($newArray[$i]=>$newArray);
}
I'm confused about what you want to do with non-numeric keys (ie, x in your example). But in any case using array references will help
$array = array( 0 => 'foo', 1 => 'bar', x => 'foobar' );
$out = array();
$curr = &$out;
foreach ($array as $key => $value) {
$curr[$value] = array();
$curr = &$curr[$value];
}
print( "In: \n" );
print_r($array);
print( "Out : \n" );
print_r($out);
Prints out
In:
Array
(
[0] => foo
[1] => bar
[x] => foobar
)
Out :
Array
(
[foo] => Array
(
[bar] => Array
(
[foobar] => Array
(
)
)
)
)
You can use a recursive function so that you're not iterating through the array each step. Here's such a function I wrote.
function expand_arr($arr)
{
if (empty($arr))
return array();
return array(
array_shift($arr) => expand_arr($arr)
);
}
Your question is a little unclear since in your initial statement you're using the next value in the array as the next step down's key and then at the end of your example you're using the original key as the only key in the next step's key.

Multidimenssion array compare two arrays and update first array value

I want to filter a array by a number and update its status in the first array.
I have two array $arr1,$arr2
$arr1 = array(
0=>array('number'=>100,name=>'john'),
1=>array('number'=>200,name=>'johnny')
);
$arr2= array(
0=>array('number'=>300,name=>'r'),
1=>array('number'=>100,name=>'b'),
2=>array('number'=>200,name=>'c')
);
Final output should be an array like this
$arr1 = array(
0=>array('number'=>100,name=>'b'),
1=>array('number'=>200,name=>'c')
);
Any ideas to start off please ?
For specialized array modifications like this, the method of choice is array walk. It allows you to apply a custom function to each element in a given array.
Now, because of your data format, you will have to do a loop. Wrikken is asking if you can retrieve or transform the data to provide faster access. The algorithm below is O(n^2): it will require as many cycles as there are elements in the first array times the number of elements in the second array, or exactly count($arr1) * count($arr2).
function updateNameFromArray($element, $key, $arr2) {
foreach($arr2 as $value) {
if($value['number'] == $element['number']) {
$element['name'] == $value['name'];
break;
}
}
}
array_walk($arr1, "updateNameFromArray", $arr2);
Now, what Wrikken is suggesting is that if your arrays can be changed to be keyed on the 'number' property instead, then the search/replace operation is much easier. So if this were your data instead:
$arr1 = array(
100=>array('number'=>100,name=>'john'),
200=>array('number'=>200,name=>'johnny')
);
// notice the keys are 100 and 200 instead of 0,1
$arr2= array(
300=>array('number'=>300,name=>'r'),
100=>array('number'=>100,name=>'b'),
200=>array('number'=>200,name=>'c')
);
// notice the keys are 300, 100 and 200 instead of 0,1, 2
Then you could do this in O(n) time, with only looping over the first array.
foreach($arr1 as $key => $value) {
if(isset($arr2[$key])) {
$value['number'] = $arr2[$key]['number'];
}
}
Try this. It's not that clean but i think it would work.
<?php
$arr1 = array(0=>array('number'=>100,'name'=>'john'),1=>array('number'=>200,'name'=>'johnny'));
$arr2= array(0=>array('number'=>300,'name'=>'r'),1=>array('number'=>100,'name'=>'b'),2=>array('number'=>200,'name'=>'c'));
foreach( $arr1 as $key=>$data1 )
{
foreach( $arr2 as $key2=>$data2 )
{
if( $data1['number'] == $data2['number'] )
{
$arr1[$key]['name'] = $arr2[$key2]['name'];
}
}
}
print_r( $arr1 );
?>
the output would be :
Array
(
[0] => Array
(
[number] => 100
[name] => b
)
[1] => Array
(
[number] => 200
[name] => c
)
)
There isn't really a simple way for this to be accomplished with generic PHP functions, so, You might need to create mapping arrays.
The way I would approach this, is creating a loop that goes through the first array, and maps the number value as a key to the index of it's place in $arr1 giving you:
$tmp1 = array();
foreach ($arr1 as $key => $number_name) {
$tmp1[$number_name['number']] = $key;
}
This should give you an array that looks like
$tmp1 [
100 => 0,
200 => 1
];
Then I would loop through the second array, get the number value, if that existed as a key in $tmp1, get the associated value (being the key for $arr1), and use that to update the name in $arr1.
// Loop through $arr2
foreach ($arr2 as $number_name) {
// Get the number value
$number = $number_name['number'];
// Find the $arr1 index
if (isset($tmp1[$number])) {
$arr1_key = $tmp1[$number];
// Set the $arr1 name value
$arr1[$arr1_key]['name'] = $number_name['name'];
}
}
<?php
//Set the arrays
$arr1 = array(
array('number'=>100,'name'=>'john'),
array('number'=>200,'name'=>'johnny')
);
$arr2= array(
array('number'=>300,'name'=>'r'),
array('number'=>100,'name'=>'b'),
array('number'=>200,'name'=>'c')
);
// use a nested for loop to iterate and compare both arrays
for ($i=0;$i<count($arr1);$i++):
for ($j=0;$j<count($arr2);$j++):
if ($arr2[$j]['number']==$arr1[$i]['number'])
$arr1[$i]['name']=$arr2[$j]['name'];
endfor;
endfor;
print_r($arr1);
OUTPUT:
Array (
[0] => Array ( [number] => 100 [name] => b )
[1] => Array ( [number] => 200 [name] => c )
)
That being said, you should probably reconsider the very way your data is structured. Do you really need a multi-dimensional array or can you use a simple associative array, like so:
// set the arrays
$arr1 = array(
'john'=>100,
'johnny'=>200
);
$arr2 = array(
'r'=>300,
'b'=>100,
'c'=>200
);
// find values in arr2 common to both arrays
$arr3 = array_intersect($arr2, $arr1);
// change the key of arr1 to match the corresponding key in arr2
foreach ($arr3 as $key=>$value) {
$old_key = array_search($value, $arr1);
$arr1[$key]=$arr1[$old_key];
unset($arr1[$old_key]);
}
print_r($arr1);
OUTPUT:
Array (
[b] => 100
[c] => 200
)

PHP multidimensional array to simple array

Which method is best practice to turn a multidimensional array
Array ( [0] => Array ( [id] => 11 ) [1] => Array ( [id] => 14 ) )
into a simple array? edit: "flattened" array (thanks arxanas for the right word)
Array ( [0] => 11 [1] => 14 )
I saw some examples but is there an easier way besides foreach loops, implode, or big functions? Surely there must a php function that handles this. Or not..?
$array = array();
$newArray = array();
foreach ( $array as $key => $val )
{
$temp = array_values($val);
$newArray[] = $temp[0];
}
See it here in action: http://viper-7.com/sWfSbD
Here you have it in function form:
function array_flatten ( $array )
{
$out = array();
foreach ( $array as $key => $val )
{
$temp = array_values($val);
$out[] = $temp[0];
}
return $out;
}
See it here in action: http://viper-7.com/psvYNO
You could use array_walk_recursive to flatten an array.
$ret = array();
array_walk_recursive($arr, function($var) use (&$ret) {
$ret[] = $var;
});
var_dump($ret);
If you have a multidimensional array that shouldn't be a multidimensional array (has the same keys and values) and it has multiple depths of dimension, you can just use recursion to loop through it and append each item to a new array. Just be sure not to get a headache with it :)
Here's an example. (It's probably not as "elegant" as xdazz", but it's an alternate without using "use" closure.) This is how the array might start out like:
Start
array (size=2)
0 =>
array (size=1)
'woeid' => string '56413072' (length=8)
1 =>
array (size=1)
'woeid' => string '56412936' (length=8)
Then you might want to have something like this:
Target
array (size=2)
0 => string '56413072' (length=8)
1 => string '56412936' (length=8)
You can use array_walk_recursive
Code
$woeid = array();
array_walk_recursive($result['results']['Result'], function ($item, $key, $woeid) {
if ($key == 'woeid') {
$woeid[] = $item;
}
}, &$woeid);

Categories