Merge multple arrays from one result into a single array in PHP - php

I'm really sorry to bug you, put I've got a problem that I've been trying to resolve for quite some time now. I've done some research and have found things like array_merge but it doesn't appear to help me.
Anyway, enough waffle. I have a result of a query that looks something like this:
Array
(
[0] => STRINGA
)
Array
(
[0] => STRINGA
[1] => STRINGB
)
Array
(
[0] => STRINGA
[1] => STRINGB
[2] => STRINGC
)
Array
(
[0] => STRINGD
[1] => STRINGC
[2] => STRINGA
[3] => STRINGB
[4] => STRINGE
[5] => STRINGF
)
How can I combine the above into one array so that the result will look more like:
Array
(
[0] => STRINGA
[1] => STRINGB
[2] => STRINGC
[3] => STRINGD
[4] => STRINGE
[5] => STRINGF
)
Duplicates in the original arrays can be ignored as I only need the string to be placed into the new array once.
Any help would be massively appreciated.
Thank you.
EDITED: This is the block of code that brings out the result from the database:
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
foreach($row as $splitrow) {
if(NULL != $splitrow) {
$therow = explode(';',$splitrow);
}
//print_r retrieves result shown above
print_r($therow);
}
}

$bigarray = array(
array (
0 => 'STRINGA',
),
array (
0 => 'STRINGA',
1 => 'STRINGB',
),
array(
0 => 'STRINGA',
1 => 'STRINGB',
2 => 'STRINGC',
)
);
$result = array_values(
array_unique(
array_merge( $bigarray[0], $bigarray[1], $bigarray[2] )
)
);
// array_merge will put all arrays together, including duplicates
// array_unique removes duplicates
// array_values will sort out the indexes in ascending order (1, 2, 3 etc...)

$bigarray = array();
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
foreach($row as $value){
if($value != NULL){
$therow = explode(';',$value);
foreach($therow as $key=>$values){
//push the value into the single array 'bigarray'
array_push($bigarray, $values);
}
}
}
}
//remove duplicates
$uniquearray = array_unique($bigarray);
//reset key values
$indexedarray = array_values($uniquearray);
print_r($indexedarray);
Thanks to all of those that helped, much appreciated!

Related

How to combine 2 arrays of different lengths while dropping part of one array?

I have 2 arrays
array 1: Array ( [0] => Merc [1] => # [2] => BM [3] => & [4] => Lotus )
array 2: Array ( [0] => 6740 [1] => 4565 [2] => 3423 )
The goal is to combine the 2 arrays and end up with:
$result = ['Merc' => 6740, 'BM' => 4565, 'Lotus' => 3423];
There is a fair amount of guidance on this already, I know, and I have read up on it but array manipulation is new to me and somehow I just cannot get my head around the logic and syntax.
Please could someone with an experienced eye tell me where I am going wrong.
I have tried:
...
//// lets echo the arrays to make sure they are correct
print_r($car);?><br><?php
print_r($part);?><br><?php
//// lets combine the 2 arrays to get an associative array
$result = [];
for($i = 0; $i < count($car); $i++){
if (($car[$i] == "&")||($car[$i] == "#")){
$i = ($i + 1);
}
foreach($car as $car) {
foreach($part as $part) {
$result[] = array(
$car => $part,
);
}
}
}
print_r($result);
The output for this is:
Array ( [0] => Array ( [Merc] => 6740 ) [1] => Array ( [BM] => 4565 ) [2] => Array ( [Lotus] => 3423 ))
The special characters to be stripped will only ever be # or &
Filter out the unwanted elements and combine them.
Code: (Demo)
$cars=['Merc','#','BM','&','Lotus'];
$parts=[6740,4565,3423];
$cars=array_diff($cars,['#','&']);
var_export(array_combine($cars,$parts));
Output:
array (
'Merc' => 6740,
'BM' => 4565,
'Lotus' => 3423,
)
p.s. You could also filter with ctype_alpha() like this: (Demo)
$cars=array_filter($cars,'ctype_alpha'); // only retain elements that are fully comprised of letters

php mysqli result into an array not working as expected

I have a php /mysqli query and I want to populate an array with the results:
$query3 ="SELECT * FROM conditions";
$results = array();
if ($result = mysqli_query($conn, $query3)){
while($row = mysqli_fetch_assoc($result))
{
$results[] = $row;
}
}
print_r($results);
Something is wrong here -its making arrays within arrays I think. (to be honest I am confused by this result)
How do I do this correctly!
Array (
[0] => Array ( [condition_id] => 1 [condition_name] => Epilepsy )
[1] => Array ( [condition_id] => 2 [condition_name] => ASD )
[2] => Array ( [condition_id] => 3 [condition_name] => BESD )
[3] => Array ( [condition_id] => 4 [condition_name] => HI )
[4] => Array ( [condition_id] => 5 [condition_name] => Medical )
[5] => Array ( ...
Thanks for all the help - now how should I create what I actually want which is one array with key=>value like this:
array (1=>epilepsy, 2=>ASd...) - the numbers refer to the primary key.
How do I populate an array from this query please?
Change your code as below :
while($row = mysqli_fetch_assoc($result))
{
$results[$row['condition_id']] = $row['condition_name'];
}
Move to PDO, Luke.
$results = $pdo->query("SELECT FROM conditions")->fetchAll(PDO::FETCH_KEY_PAIR);
print_r($results);
Whoops! Is that all the code?

PHP loop to get the data I need

I am using an API and am using a few foreach loops to get to the stage that I am at right now. Please see code below with my comments and also the results that I am getting below that.
// get recent_games api data
$recent_games_data = $player->recent_games();
//start arrays for below
$matches = array();
$gameType = array();
$myData = array();
// using foreach loops to dig in to api data
foreach($recent_games_data['gameStatistics']['array'] as $key_match_data => $value_match_data) {
$matches[] = $value_match_data['statistics'];
}
foreach($matches as $key_match) {
$gameType[] = $key_match['array'];
}
foreach ($gameType as $keyz) {
$myData[] = $keyz;
}
The $mydata array outputs this data below.
Array
(
[0] => Array
(
[0] => Array
(
[statType] => TRUE_DAMAGE_DEALT_TO_CHARACTER
[dataVersion] => 0
[value] => 3351
[futureData] =>
)
[1] => Array
(
[statType] => ASSISTS
[dataVersion] => 0
[value] => 14
[futureData] =>
)
[2] => Array
(
[statType] => NUM_DEATHS
[dataVersion] => 0
[value] => 3
[futureData] =>
)
)
[1] => Array
(
[0] => Array
(
[statType] => TRUE_DAMAGE_DEALT_TO_CHARACTER
[dataVersion] => 0
[value] => 331
[futureData] =>
)
[1] => Array
(
[statType] => ASSISTS
[dataVersion] => 0
[value] => 4
[futureData] =>
)
[2] => Array
(
[statType] => NUM_DEATHS
[dataVersion] => 0
[value] => 7
[futureData] =>
)
)
Of course there is much more data but this is basically what I have now. The first array [0] is each match and the second array are the statistics for that match. What I want is how do I get the statistics of each match without hardcoding the match array number, for example below.
$myData[0][0]['statType']
Let me know if you need more info and thank you.
EDIT: sorry for to mention that as new statistics data gets added to the api, the index number changes. IE TRUE_DAMAGE_DEALT_TO_CHARACTER is [0] to begin with but then may change to [1] or [2] etc.
Consider implementing a class for your stats items after parsing through the data (independent of individual match information keys):
class Stat_Item {
function __construct($id, $info) {
$this->id = $id;
if(!empty($info['damage'])
$this->damage_dealt = $info['damage'];
if(!empty($info['assists']))
$this->assists = $info['assists'];
if(!empty($info['deaths']))
$this->deaths = $info['deaths'];
}
}
$parsed_items = array();
foreach($mydata as $match_id => $match) {
$info = array();
foreach($match as $data_point) {
switch($data_point['statType']) {
case TRUE_DAMAGE_DEALT_TO_CHARACTER:
$info['damage'] = $data_point['value'];
break;
case ASSISTS:
$info['assists'] = $data_point['value'];
break;
case NUM_DEATHS:
$info['deaths'] = $data_point['value'];
break;
}
$parsed_items[] = new Stat_Item($match, $info);
}
}
Other than looping through them all, I don't see any way for you to get a particular match without calling it by its index.
You don't need several foreach loops - you can add to all three arrays in a single one. Also, it looks like $gameType and $myData end up containing the same data.
foreach($recent_games_data['gameStatistics']['array'] as $key_match_data => $value_match_data) {
$matches[] = $value_match_data['statistics'];
$gameType[] = $value_match_data['statistics']['array'];
$myData[] = $value_match_data['statistics']['array'];
}
I don't really understand why you don't just put it into the same array so you can access it easily, though:
foreach($recent_games_data['gameStatistics']['array'] as $key_match_data => $value_match_data) {
$matches[] = array('statistics' => $value_match_data['statistics'], 'data' => $value_match_data['statistics']['array']);
}

Problem with Building Arrays in Different Coding Styles

I'm having a strange problem while building arrays. I start off with an array that looks like this:
Array (
[0] => Array (
[tag_id] => 19
[tag_translation_id] => 12
[fk_language_id] => 1
[fk_tag_id] => 19
[tag_name] => test
)
[1] => Array (
[tag_id] => 20
[tag_translation_id] => 14
[fk_language_id] => 1
[fk_tag_id] => 20
[tag_name] => testa
)
[2] => Array (
[tag_id] => 20
[tag_translation_id] => 15
[fk_language_id] => 3
[fk_tag_id] => 20
[tag_name] => fdfda
)
)
What I want to do is merge each result with the same tag_id into a single array. This works:
$tags = array();
foreach($results->as_array() as $key=>$result)
{
if(!in_array($result['tag_id'], $tags))
{
$tags[$result['tag_id']] = array();
}
}
foreach($results->as_array() as $result)
{
array_push($tags[$result['tag_id']], array($result['fk_language_id'] , $result['tag_name']));
}
Here is the intended result:
Array (
[19] => Array (
[0] => Array (
[0] => 1
[1] => test
)
)
[20] => Array (
[0] => Array (
[0] => 1
[1] => testa
)
[1] => Array (
[0] => 3
[1] => fdfda
)
)
)
However, I've got two loops here, and I know this isn't ideal. Why do THESE not work??
$tags = array();
foreach($results->as_array() as $key=>$result)
{
$tags[$result['tag_id']] .= array($result['fk_language_id'] , $result['tag_name']);
}
With this example I get two empty arrays...
Array ( [19] => Array [20] => ArrayArray )
Or even...
$tags = array();
foreach($results->as_array() as $key=>$result)
{
if(!in_array($result['tag_id'], $tags))
{
$tags[$result['tag_id']] = array();
}
array_push($tags[$result['tag_id']], array($result['fk_language_id'] , $result['tag_name']));
}
Which for some reason overwrites the first value of the second array with the second value of the second array.
Array (
[19] => Array (
[0] => Array (
[0] => 1
[1] => test
)
)
[20] => Array (
[0] => Array (
[0] => 3
[1] => fdfda
)
)
)
What am I doing wrong in the second 2 examples?
To answer your question, your second method fails because you're using the incorrect .= operator. Your third method fails because your !in_array check is always false (it checks whether the value is in the array, not whether the key is set) and overwrites the array each iteration. You only really need this (as mentioned by others, in pseudo-code):
$result = array();
foreach ($array as $values) {
$result[$values['key']][] = array($values['foo'], $values['bar']);
}
The .= operator is string concatenation. Arrays are merged with +=.
If I understand the issue correctly, the code should go like this:
$tags = array();
foreach ($results as $result)
$tags[$result['tag_id']][] = array($result['fk_language_id'], $result['tag_name']);
$tags = array();
foreach($results->as_array() as $key=>$result)
{
$tags[$result['tag_id']] .= array($result['fk_language_id'] , $result['tag_name']);
}
you cannot add a value to an array with the .= (dot equal) operator.
why are you doing $results->as_array() ????
do simply:
foreach($results as $key=>$result) {
Instead of using .= try using []
$tags = array();
foreach ($results as $result)
{
if(!isset($tags[$result['tag_id']]))
$tags[$result['tag_id']] = array();
$tags[$result['tag_id']][] = array($result['fk_language_id'], result['tag_name']);
}
.= is to concatinate a string
+= is to concatinate a number
[] is to concatinate to an array
Hope this helps?
Edit: Noticed that it "might" fail if the tag_id doesn't already exist in the array, so it might be worth just checking first and setting it to an array just in case.

How can I create multidimensional arrays from a string in PHP?

So My problem is:
I want to create nested array from string as reference.
My String is "res[0]['links'][0]"
So I want to create array $res['0']['links']['0']
I tried:
$result = "res[0]['links'][0]";
$$result = array("id"=>'1',"class"=>'3');
$result = "res[0]['links'][1]";
$$result = array("id"=>'3',"class"=>'9');
when print_r($res)
I see:
<b>Notice</b>: Undefined variable: res in <b>/home/fanbase/domains/fanbase.sportbase.pl/public_html/index.php</b> on line <b>45</b>
I need to see:
Array
(
[0] => Array
(
[links] => Array
(
[0] => Array
(
[id] => 1
[class] => 3
)
)
)
[1] => Array
(
[links] => Array
(
[0] => Array
(
[id] => 3
[class] => 9
)
)
)
)
Thanks for any help.
So you have a description of an array structure, and something to fill it with. That's doable with something like:
function array_create(&$target, $desc, $fill) {
preg_match_all("/[^\[\]']+/", $desc, $uu);
// unoptimized, always uses strings
foreach ($uu[0] as $sub) {
if (! isset($target[$sub])) {
$target[$sub] = array();
}
$target = & $target[$sub];
}
$target = $fill;
}
array_create( $res, "[0]['links'][0]", array("id"=>'1',"class"=>'3') );
array_create( $res, "[0]['links'][1]", array("id"=>'3',"class"=>'9') );
Note how the array name itself is not part of the structure descriptor. But you could theoretically keep it. Instead call the array_create() function with a $tmp variable, and afterwards extract() it to achieve the desired effect:
array_create($tmp, "res[0][links][0]", array(1,2,3,4,5));
extract($tmp);
Another lazy solution would be to use str_parse after a loop combining the array description with the data array as URL-encoded string.
I have a very stupid way for this, you can try this :-)
Suppose your string is "res[0]['links'][0]" first append $ in this and then put in eval command and it will really rock you. Follow the following example
$tmp = '$'.'res[0]['links'][0]'.'= array()';
eval($tmp);
Now you can use your array $res
100% work around and :-)
`
$res = array();
$res[0]['links'][0] = array("id"=>'1',"class"=>'3');
$res[0]['links'][0] = array("id"=>'3',"class"=>'9');
print_r($res);
but read the comments first and learn about arrays first.
In addition to mario's answer, I used another function from php.net comments, together, to make input array (output from jquery form serializeArray) like this:
[2] => Array
(
[name] => apple[color]
[value] => red
)
[3] => Array
(
[name] => appleSeeds[27][genome]
[value] => 201
)
[4] => Array
(
[name] => appleSeeds[27][age]
[value] => 2 weeks
)
[5] => Array
(
[name] => apple[age]
[value] => 3 weeks
)
[6] => Array
(
[name] => appleSeeds[29][genome]
[value] => 103
)
[7] => Array
(
[name] => appleSeeds[29][age]
[value] => 2.2 weeks
)
into
Array
(
[apple] => Array
(
[color] => red
[age] => 3 weeks
)
[appleSeeds] => Array
(
[27] => Array
(
[genome] => 201
[age] => 2 weeks
)
[29] => Array
(
[genome] => 103
[age] => 2.2 weeks
)
)
)
This allowed to maintain numeric keys, without incremental appending of array_merge. So, I used sequence like this:
function MergeArrays($Arr1, $Arr2) {
foreach($Arr2 as $key => $Value) {
if(array_key_exists($key, $Arr1) && is_array($Value)) {
$Arr1[$key] = MergeArrays($Arr1[$key], $Arr2[$key]);
}
else { $Arr1[$key] = $Value; }
}
return $Arr1;
}
function array_create(&$target, $desc, $fill) {
preg_match_all("/[^\[\]']+/", $desc, $uu);
foreach ($uu[0] as $sub) {
if (! isset($target[$sub])) {
$target[$sub] = array();
}
$target = & $target[$sub];
}
$target = $fill;
}
$input = $_POST['formData'];
$result = array();
foreach ($input as $k => $v) {
$sub = array();
array_create($sub, $v['name'], $v['value']);
$result = MergeArrays($result, $sub);
}

Categories