How to convert multiple array to single array [duplicate] - php

This question already has answers here:
Convert array of single-element arrays to a one-dimensional array
(8 answers)
Closed 3 years ago.
Sorry for asking this silly question here. I am very new to PHP language.
I am trying to know how can i convert the array.
I want to convert this array to single array like.
Convert this :-
Array ( [0] => user )
Array ( [0] => user1 )
Array ( [0] => user2 )
Array ( [0] => user3 )
Array ( [0] => user8 )
Array ( [0] => user7 )
Array ( [0] => user6 )
Convert To :-
Array("user", "user1", "user2", "user3", "user4", "user5", "user6");

To "Merge" multiple arrays into one, you can use array_merge()
A good example would be:
$array_1 = array('user');
$array_2 = array('user1');
$array_3 = array('user2');
$combined_array = array_merge($array1,$array_2,$array_3);
var_dump($combined_array);

Something like this should do:
while($row = $result->fetch_array(MYSQLI_NUM)) {
$users[] = $row[0];
}

Pack or collect all arrays into a parent array.
Then you only need to pass an array as a parameter when calling array_merge.
Update: it is better to use array_column.
$arr = [];
$arr[] = array('user');
$arr[] = array('user1');
$arr[] = array('user2');
$one_dim_array = array_merge(...$arr);
//or better
$one_dim_array = array_column($arr,0);
echo "<pre>".var_export($one_dim_array, true);
Result:
array (
0 => 'user',
1 => 'user1',
2 => 'user2',
)
Try it yourself : Sandbox

Another alternative, aside from array_merge, for the case of an arbitrary number of subarrays, you could use array_reduce and build your final array:
$inArray = [['user'],['user1'],['user2'],['user3'],['user8'],['user7'],['user6']];
$inArray = array_reduce($inArray, function($arr, $elem){
$arr[] = $elem[0];
return $arr;
});
Of course, the straightforward solution would be to use array_merge:
$inArray = array_merge(...$inArray);

Related

how to store two variables strings in 2d array in php

I'm working with multi-dimensional arrays in PHP. I want to store two string values in a two dimensional array. I have tried the following code:
$arr[][]=['string1']['string2'];
I have also tried:
$arr[][]="string1","string2";
Due to the comma I have a syntax error.
How can I fix this?
$arr = [];
$arr[] = ['string1'];
$arr[] = ['string2'];
// or simply
// $arr = [['string1'], ['string2']];
print_r($arr);
// output:
Array ( [0] => Array ( [0] => string1 ) [1] => Array ( [0] => string2 ) )
If you want 'string1' and 'string2' to be the key and subkey in an array then you use:
$arr = [];
$arr['string1']['string2'] = 'somevalue';

array_column with an array of objects [duplicate]

This question already has answers here:
PHP. Is it possible to use array_column with an array of objects
(5 answers)
Closed 6 years ago.
TLDR; My question is different from PHP. Is it possible to use array_column with an array of objects. I want to only change the keys within the array and keep the objects, not having the objects' values stored in a separate array like the given answer.
I would like to set the keys, of an array with objects, to a value of the object. So this array:
$array = Array
(
[0] => stdClass Object
(
[id] = 12234
[value] = some value
)
[1] => stdClass Object
(
[id] = 12994
[value] = some value
)
)
Should become:
$array = Array
(
[12234] => stdClass Object
(
[id] = 12234
[value] = some value
)
[12994] => stdClass Object
(
[id] = 12994
[value] = some value
)
)
Now I could loop over the array, but I would prefer a more cleaner solution. I thought this should work:
$newArray = array_column($array, null, 'id');
The only problem is I'm having an array of objects instead of an array of arrays and I'm not using PHP7 yet. Now I found a similar question over here
PHP. Is it possible to use array_column with an array of objects
But the thing is it doesn't return what I expected. Cause this:
$newArray = array_map(function($o) {
return is_object($o) ? $o->id : $o['id'];
}, $array);
Returns
Array
(
[0] => 12234
[1] => 12994
)
Anyone who knows a clean solution (so without a for or foreach loop) for this?
$array = array_combine(array_map(function ($o) { return $o->id; }, $array), $array);
Whether this is really a lot better than a simple foreach loop, aside from "but, but, functional programming...!", is debatable.
// your data
$array = array(
(object) array(
"id" => "12234",
"value" => "some value",
),
(object) array(
"id" => "12235",
"value" => "some value",
),
(object) array(
"id" => "12236",
"value" => "some value",
),
);
// let's see what we have
print_r($array);
// here comes the magic ;-)
function key_flip_array($array, $keyname){
$keys = array_map(function($item, $keyname){
return (is_object($item) && isset($item->{$keyname}) ? $item->{$keyname} : (is_array($item) && isset($item[$keyname]) ? $item[$keyname] : null));
}, $array, array_fill(0, count($array), $keyname));
return array_combine($keys, $array);
}
$array = key_flip_array($array, "id");
// i hope this is what you wish to see
print_r($array);

remove same values from an array [duplicate]

This question already has answers here:
Remove duplicates from Array
(2 answers)
Closed 9 years ago.
I have an array like this
Array
(
[0] => u1,u2
[1] => u2,u1
[2] => u4,u3
[3] => u1,u3
[4] => u1,u2
)
I want to remove similar values from the array
I want an out put like
Array
(
[0] => u1,u2
[1] => u4,u3
[2] => u1,u3
)
I tried to loop thru the input array, sort the value of the indexes alphabetically and then tried array_search to find the repeated values. but never really got the desired output
any help apprecated
You cannot use array_unique() alone, since this will only match exact duplicates only. As a result, you'll have to loop over and check each permutation of that value.
You can use array_unique() to begin with, and then loop over:
$myArray = array('u1,u2', 'u2,u1', 'u4,u3', 'u1,u3', 'u1,u2');
$newArr = array_unique($myArray);
$holderArr = array();
foreach($newArr as $val)
{
$parts = explode(',', $val);
$part1 = $parts[0].','.$parts[1];
$part2 = $parts[1].','.$parts[0];
if(!in_array($part1, $holderArr) && !in_array($part2, $holderArr))
{
$holderArr[] = $val;
}
}
$newArr = $holderArr;
The above code will produce the following output:
Array (
[0] => u1,u2
[1] => u4,u3
[2] => u1,u3
)
Use array_unique() PHP function:
http://php.net/manual/en/function.array-unique.php
Use the function array_unique($array)
array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )
php manual
since u1,u2 !== u2,u1
$array=array('u1,u2','u2,u1','u4,u3','u1,u3','u1,u2');
foreach($array as $k=>$v)
{
$sub_arr = explode(',',$v);
asort($sub_arr);
$array[$k] = implode(',',$sub_arr);
}
$unique_array = array_unique($array);
//$unique_array = array_values($unique_array) //if you want to preserve the ordered keys

How to get all values from one array which do not exist in another array?

How to get the values from an array that are NOT in another array in PHP?
My current aproach have bad time complexity. Is there an inbuilt php function that can solve my problem?
Example:
$a1 = array(1,2,3,4);
$a2 = array(3,4,5,6,7);
Result:
[5,6,7];
array_diff is your friend.
Returns an array containing all the entries from array1 that are not present in any of the other arrays.
$a1 = array(1,2,3,4);
$a2 = array(3,4,5,6,7);
$result = array_diff($a2, $a1);
print_r($result);
Will output:
Array
(
[2] => 5
[3] => 6
[4] => 7
)
And if you reverse the parameters like this:
array_diff($a1, $a2)
It will output:
Array
(
[0] => 1
[1] => 2
)

PHP Convert multidimensional array to match format of another

I have two arrays, one is generated by using explode() on a comma separated string and the other is generated from result_array() in Codeigniter.
The results when doing print_r are:
From explode():
Array
(
[0] => keyword
[1] => test
)
From database:
Array
(
[0] => Array
(
[name] => keyword
)
[1] => Array
(
[name] => test
)
)
I need them to match up so I can use array_diff(), what's the best way to get them to match? Is there something other than result_array() in CI to get a compatible array?
You could create a new array like this:
foreach($fromDatabase as $x)
{
$arr[] = $x['name'];
}
Now, you will have two one dim arrays and you can run array_dif.
$new_array = array();
foreach ($array1 as $line) {
$new_array[] = array('name' => $line);
}
print_r($new_array);
That should work for you.

Categories