How to simplify an array with PHP - php

Seems like a pretty basic question, but how can I simplify an array such as:
Array
(
[0] => Array
(
[blue_dog_1] => 2
)
[1] => Array
(
[red_dog_1] => 4
)
[2] => Array
(
[red_dog_2] => 6
)
)
To be like:
Array
(
[blue_dog_1] => 2
[red_dog_1] => 4
[red_dog_2] => 6
)
Thanks in advance.

Try this way to make it single dimension from multi dimension using array_merge
$singleD = array_reduce($multiD, 'array_merge', array());
OR
$singleD = call_user_func_array('array_merge', $multiD);

Try this,
foreach($array as $sub_val)
{
foreach($sub_val as $key=>$val)
{
$new_array[$key] = $val;
}
}
print_r($new_array);

To accomplish this you can simply use array union operator.
$oldData = array(
0 => array('blue_dog_1'=>2),
1 => array('red_dog_1'=>4),
2 => array('red_dog_2'=>6)
);
$newData = array();
foreach ($oldData as $arrayData) {
$newData += $arrayData;
}
print_r($newData);

Related

add item array in a exist array php [duplicate]

This question already has answers here:
Merge row data from multiple arrays
(6 answers)
Closed 4 months ago.
I need to add an item array in a exist array. When i try to add i get something like this, using array_push
Array
(
[0] => Array
(
[totalp] => 3.26
[mes] => Novembro
)
[1] => Array
(
[totalp] => 2.66
[mes] => Dezembro
)
[2] => Array
(
[0] => Array
(
[bonus] => 2.6
)
[1] => Array
(
[bonus] => 4.16
)
)
)
but i need this.
Array (
[0] => Array
(
[totalp] => 3.26
[mes] => Novembro
[bonus] => 2.6
)
[1] => Array
(
[totalp] => 2.66
[mes] => Dezembro
[bonus] => 4.16
) )
follow my code.
$arrRows = array();
while ($dados = $resultp ->fetch_array(MYSQLI_ASSOC)) {
$arrRows[] = $dados;//getting totalp and mes here
}
$arrRows1 = array();
while ($dados = $resultb ->fetch_array(MYSQLI_ASSOC)) {
$arrRows1[]=$dados; //getting bonus here
}
array_push($arrRows,$arrRows1); // first example, but i dont need this way.
print_r($arrRows);
thankyou
Use array_map
$res = array_map('array_merge', $arrRows, $arrRows1);
demo
<?php
$newdata = array (
0 => array('totalp'=>'3.26','mes' => 'Novembro'),
1 => array('totalp'=>'2.66','mes' => 'Dezembro')
);
foreach($newdata as $key => $value){
$newdata[$key]['Bonus'] = "12";
}
echo '<pre>';
print_r($newdata);
Check it On LIVE DEMO
Here is code that add bonus in multidimensional array
<?php
$array = array(
array(
"totalp" => "3.26",
"mes" => "Novembro"
),
array(
"totalp" => "3.26",
"mes" => "Novembro"
)
);
for ($i=0; $i < sizeof($array); $i++) {
$array[$i]['bonus'] = "2.2"; // here is you can get output from another array or variable
}
echo "<pre>";
print_r($array);
?>
See Output
Try this,
foreach($arrRows as $key=>$row){
$arrRows[$key]['bonus'] = $arrRows1[$key]['bonus'];
}
echo "<pre>";
print_r($arrRows);
echo "</pre>";
Use array merge like below code snippet:
$out = array();
foreach ($arrRows as $key => $value){
$out[] = array_merge((array)$arrRows1[$key], (array)$value);
}
print_r($out);
You can check this url for reference: Array merge on multidimensional array

Check an array value exists another array key in PHP

I have two arrays with the following values,
First Array:
Array
(
[Strongly Agree] => 100
)
Second Array:
Array
(
[0] => Strongly Agree
[1] => Agree
[2] => Neither Agree or Disagree
[3] => Strongly Disagree
)
I need the output should like this,
Array (
[0] => 100
[1] => 0
[2] => 0
[3] => 0
)
Try like
foreach($array2 as $key => $value) {
$temp = array_key_exists($value, $array2) ? $array1[$value] : 0;
$newArr[$key] = $temp;
}
array key exists won't trigger notices
$sample = array('Strongly Agree' => 100);
$alternatives = array( 'Strongly Agree', 'Agree', 'Neither Agree or Disagree', 'Strongly Disagree');
$output=array();
foreach($alternatives as $alternative) {
$output[$alternative] = array_key_exists($alternative, $sample)? $sample[$alternative]:0;
}
print_r($output);
Try
$arr2 = array_merge(array_fill_keys($arr2, 0), $arr1);
See demo here

Find the difference from two arrays in php

--$arr1----
Array
(
[0] => Array
(
[id] => 1
[Name] => AAA
)
[1] => Array
(
[id] => 6
[Name] => BBB
)
)
--$arr2---
Array
(
[0] => Array
(
[id] => 1
[Name] => AAA
)
[1] => Array
(
[id] => 6
[Name] => BBB
)
[2] => Array
(
[id] => 46
[Name] => CCC
)
)
I would like the final result as following. Is there anyone can help me?
--Final Result--
Array
(
[0] => Array
(
[id] => 46
[Name] => CCC
)
)
UPDATE---
In this case, the result of array_diff($arr1,$arr2) is empty.
The easiest way is Mark Baker's solution or just write your own simple function:
Code:
function arrdiff($a1, $a2) {
$res = array();
foreach($a2 as $a) if (array_search($a, $a1) === false) $res[] = $a;
return $res;
}
print_r(arrdiff($arr1, $arr2));
Output:
Array
(
[0] => Array
(
[id] => 46
[name] => CCC
)
)
$arr1 = array(array('id' => 1, 'Name' => 'AAA'),
array('id' => 6, 'Name' => 'BBB')
);
$arr2 = array(array('id' => 1, 'Name' => 'AAA'),
array('id' => 6, 'Name' => 'BBB'),
array('id' => 46, 'Name' => 'CCC')
);
$results = array_diff(array_map('serialize',$arr2),array_map('serialize',$arr1));
$results = array_map('unserialize',$results);
var_dump($results);
EDIT
And just for the sheer fun of it, you could use array_filter() instead of array_diff() - which means no need to serialize anything at all
$results = array_filter($arr2, function ($value) use($arr1) { return !in_array($value,$arr1); } );
var_dump($results);
You should use array_diff():
$finalResult = array_diff($arr2, $arr1);
If you need more complex comparison you may also build foreach loop and use like this:
function compareItems( $a, $b){
return $a['id'] == $b['id']; // Example compare criteria
}
$result = array();
foreach( $arr1 as $item){
foreach( $arr2 as $key => $it){
if( !compareItems( $item, $it)){
$result[] = $it; // Either build new array
unset( $arr2[$key]); // Or remove items from original array
break;
}
}
}
And than you'll probably want to implement the same with reversed order of $arr1 and $arr2.
You can solve this with array_udiff()
function arr_comp($a, $b)
{
if ($a['id'] == $b['id'])
return 0;
else if ($a['id'] > $b['id'])
return 1;
else
return -1;
}
$result = array_udiff($arr2, $arr1, 'arr_comp');
or if you don't know in which array the differences may be you can try:
$res1 = array_udiff($arr1, $arr2, 'arr_comp');
$res2 = array_udiff($arr2, $arr1, 'arr_comp');
$result = array_merge($res1, $res2);
$arrDif=array();
$i=0;
foreach($arr1 as $value)
{
if(!in_array($value, $arr2))
{
$arrDif[$i]=$value;
$i++;
}
}
Take a look at the PHP built-in function array_diff. That'll help you out :-) Just pass your two arrays, and store the array returned by array_diff(), which will contain the differences between the two arrays.
As you're using multi-dimensional arrays, look at this comment on the PHP website: http://www.php.net/manual/en/function.array-diff.php#98680.

multi-dimensional array into a single layered array PHP

I have the following array being returned
Array
(
[0] => Array
(
[uid] => 616941445
)
[1] => Array
(
[uid] => 1354124203
)
)
However I want just a single layered array, so i would like something like this.
Array
(
[0] => 616941445
[1] => 1354124203
)
foreach ($arr as $key => $val) {
$arr[$key] = $val['uid'];
}
<?php
$multi_arr = array(
array(
'uid' => 616941445
),
array(
'uid' => 1354124203
),
);
$single_arr = array();
foreach($multi_arr as $arr){
foreach($arr as $val) $single_arr[] = $val;
}
?>
As always, when you need to change two level array into one level without preserve keys:
$your2DArray = array(/* .. */);
$flatArray = array_map('array_pop', $your2DArray);
And like you want to, no loops.
foreach($arr as $key=>$val) {
$single_arr[] = $arr[$key]['uid'];
}

Count number of different strings?

I have an array that looks like
Array
(
[1] => Array
(
[0] => Date
[1] => Action
)
[2] => Array
(
[0] => 2011-01-22 11:23:19
[1] => SHARE_TWEET
)
[3] => Array
(
[0] => 2011-01-22 11:23:19
[1] => SHARE_FACEBOOK
)
and many other different values (about 10), what I want to do is I want to count the number of times a string is in the array. I was going to use array_count_values but it doesn't count multidimensional arrays.
Any other options?
This could be done by first flattening the array, and then using array_count_values() on it:
For flattening, here is the trick:
$array = call_user_func_array('array_merge', $arrays);
And then:
$counts = array_count_values($array);
Output:
array (
'Date' => 1,
'Action' => 1,
'2011-01-22 11:23:19' => 2,
'SHARE_TWEET' => 1,
'SHARE_FACEBOOK' => 1,
)
Full code:
$array = call_user_func_array('array_merge', $arrays);
var_export(array_count_values($array));
Any time you're dealing with arrays, especially with loops in PHP I can't string enough suggest you look at the array documentation, You'd be suprised how quickly you realise most of the loops in your code is unnecessary. PHP has a built in function to achieve what you're after called array_walk_recursive. And since you're using PHP5 you can use closures rather that create_function (which can be very troublesome, especially to debug, and can't be optimised by the PHP interpreter afik)
$strings = array();
array_walk_recursive($arr, function($value, $key) use (&$strings) {
$strings[$value] = isset($strings[$value]) ? $strings[$value]+1 : 1;
});
I know, unary statements aren't always clear, but this one is simple enough, but feel free to expand out the if statement.
The result of the above is:
print_r($strings);
Array
(
[Date] => 1,
[Action] => 1,
[2011-01-22 11:23:19] => 2,
[SHARE_TWEET] => 1,
[SHARE_FACEBOOK] => 1,
)
Pseudo Code
$inputArray = // your array as in the example above
foreach ($inputArray as $key => $value) {
$result[$value[1]] = $result[$value[1]] + 1;
}
var_dump($result);
Here is a way to do the job:
$arr = Array (
1 => Array (
0 => 'Date',
1 => 'Action'
),
2 => Array (
0 => '2011-01-22 11:23:19',
1 => 'SHARE_TWEET'
),
3 => Array (
0 => '2011-01-22 11:23:19',
1 => 'SHARE_FACEBOOK'
)
);
$result = array();
function count_array($arr) {
global $result;
foreach($arr as $k => $v) {
if (is_array($v)) {
count_array($v);
} else {
if (isset($result[$v])) {
$result[$v]++;
} else {
$result[$v] = 1;
}
}
}
}
count_array($arr);
print_r($result);
output:
Array
(
[Date] => 1
[Action] => 1
[2011-01-22 11:23:19] => 2
[SHARE_TWEET] => 1
[SHARE_FACEBOOK] => 1
)

Categories