php Get level array from Array Tree - php

I Have the next array:
Array
(
[1000] => Array
(
[pv] => 81
)
[1101] => Array
(
[1102] => Array
(
[pv] => 33
)
[1103] => Array
(
[pv] => 15
)
[pv] => 72
)
)
I want to make new array from this like this:
Array(
[1000] => Array(['generation'] => 1, ['pv'] => 81)
[1101] => Array(['generation'] => 1, ['pv'] => 72)
[1102] => Array(['generation'] => 2, ['pv'] => 33)
[1103] => Array(['generation'] => 2, ['pv'] => 15)
)
Generation is a level of array's deep. There are a lot of levels.
Thanks.

Be creative...
function coffee($elm, $cur_key=NULL, $level=0, &$push_arr=NULL){
if(!is_array($push_arr)) $pusH_arr = array();
$level++;
foreach($elm as $key=>$val){
if($key == 'pv'){
$push_arr[$cur_key] = array(
'generation' => $level,
'pv' => $val
);
}
else if(is_array($val)){
coffee($val, $key, $level, $push_arr);
}
else{
// unexpected value
}
}
return $push_arr;
}
// Usage:
$normalised_array = coffee($array_from_your_question);

Related

Grouping in array

I have following array..I am trying to group this.
Array
(
[0] => Array
(
[Title] => HoMedics MAN-300
[ean] => 31262006288
[upc] => 31262006288
[ProductImageName] =>
[CdnUri] =>
[ASIN] => B000050FEU
[ListPrice] => 129.99
[Status] => 2
[ActualPrice] => 129.99
[ProductID] => 5286728
)
)
I want to group this into
Array
(
[0] => Array
(
[VitalInfo]=>array(
[Title] => HoMedics MAN-300
[ean] => 31262006288
[upc] => 31262006288
[ProductImageName] =>
[CdnUri] =>
[ASIN] => B000050FEU
)
[Price]=>array(
[ListPrice] => 129.99
[Status] => 2
[ActualPrice] => 129.99
[ProductID] => 5286728
)
)
I tried but it doesn't happen as I want ...any help would be great...Thanx in advance..
try this,
CODE :
foreach($old_array as $key_old => $val_old)
{
foreach($val_old as $key => $val)
{
if(in_array($key, $VitalInfo_array))
{
$new_array[$key_old]['VitalInfo'][$key] = $val;
}
else
{
$new_array[$key_old]['Price'][$key] = $val;
}
}
}
OUTPUT :
Array
(
[0] => Array
(
[VitalInfo] => Array
(
[Title] => HoMedics MAN-300
[ean] => 31262006288
[upc] => 31262006288
[ProductImageName] =>
[CdnUri] =>
[ASIN] => B000050FEU
)
[Price] => Array
(
[ListPrice] => 129.99
[Status] => 2
[ActualPrice] => 129.99
[ProductID] => 5286728
)
)
)
DEMO
i hope it will be helpful.
Simply loop through your array and customize a new array accordingly.
Assuming $array is the original array, and $result is the customized array, try this:
foreach ($array as $k => $arr) {
$result[$k]['VitalInfo'] = array(
'Title' => $arr['Title'],
'ean' => $arr['ean'],
'upc' => $arr['upc'],
'ProductImageName' => $arr['ProductImageName'],
'CdnUri' => $arr['CdnUri'],
'ASIN' => $arr['ASIN']
);
$result[$k]['Price'] = array(
'ListPrice' => $arr['ListPrice'],
'Status' => $arr['Status'],
'ActualPrice' => $arr['ActualPrice'],
'ProductID' => $arr['ProductID']
);
}
Input : $info // Your Original Array
Ouput : $finalArr // Your Required Array
$vitalInfo = array ('Title','ean','upc','ProductImageName','CdnUri','ASIN');
$price = array ('ListPrice','Status','ActualPrice','ProductId');
$finalArr = array();
foreach ($info as $arr) {
$result = array();
foreach($arr as $k => $v){
if(in_array($k,$vitalInfo))
$result['VitalInfo'][$k] = $v;
else if(in_array($k,$price))
$result['Price'][$k] = $v;
}
$finalArr[] = $result;
}
If you are grouping this in php, have a look at these answers.
Or just copy this:
$input = [0 => [
'Title' => 'HoMedics MAN-300',
'ean' => 31262006288,
'upc' => 31262006288,
'ProductImageName' => '',
'CdnUri' => '',
'ASIN' => 'B000050FEU',
'ListPrice' => 129.99,
'Status' => 2,
'ActualPrice' => 129.99,
'ProductID' => 5286728
]];
foreach ($input as $in){
$out['VitalInfo'] = [];
$out['Price'] = [];
foreach ($in as $key => $i){
if (in_array($key, ['Title', 'ean', 'upc', 'ProductImageName', 'CdnUri', 'Asin'])){
$out['VitalInfo'][] = [$key => $i];
} else {
$out['Price'][] = [$key => $i];
}
}
$output[]=$out;
}
echo '<pre>';
var_dump($output);

multidimensional array find the given value in array in php

Array
Array (
[0] => Array (
[0] => Array ( [planoption_id] => 1 )
[1] => Array ( [planoption_id] => 2 )
[2] => Array ( [planoption_id] => 3 )
[3] => Array ( [planoption_id] => 4 )
[4] => Array ( [planoption_id] => 5 )
[5] => Array ( [planoption_id] => 6 )
[6] => Array ( [planoption_id] => 7 )
[7] => Array ( [planoption_id] => 53 )
[8] => Array ( [planoption_id] => 1 )
[9] => Array ( [planoption_id] => 2 )
)
)
how to find the value in givene array.above array is $arraypush ?
if (in_array('2', $arraypush)) {
echo "INCLUDED";
} else {
echo "-";
}
How can i do this ?
This should work for all multidimensional arrays :
function findInArray($array, $value){
foreach($array as $k=>$v){
if((is_array($v) && findInArray($v, $value)) || ($v == $value)){
return "INCLUDED";
}
}
return false;
}
I think you want like this:-
<?php
$arraypush = Array ( 0 => Array ( 0 => Array ( 'planoption_id' => 1 ), 1 => Array ( 'planoption_id' => 2 )));
echo "<pre/>";print_r($arraypush);
foreach($arraypush as $key=>$value){
foreach($value as $key1=>$val){
if(in_array('2', $val) == true){
echo "value exist at the initial array [".$key.']['.$key1.'] index and is INCLUDED.';
}
}
}
?>
Output:- https://eval.in/388240
The in_array() function in your code is searching for the data in $arraypush and the data is in $arraypush[0]
And you can't compare a value with a array in in_array() function, in yor array the 'needle' isn't a value, is an array so you have to make an array who gets the value in a format comparable whit the array you have
$arraypush = array(
0 => array(
0 => array( 'planoption_id' => 1 ),
1 => array( 'planoption_id' => 2 ),
2 => array( 'planoption_id' => 3 ),
3 => array( 'planoption_id' => 4 ),
4 => array( 'planoption_id' => 5 ),
5 => array( 'planoption_id' => 6 ),
6 => array( 'planoption_id' => 7 ),
7 => array( 'planoption_id' => 53 ),
8 => array( 'planoption_id' => 1 ),
9 => array( 'planoption_id' => 2 )
)
);
//gettig the value for the search
$foo = $_GET['foo'];
// making the 'needle' in a array format like your array definition
$foo_array = array('planoption_id' => $foo);
//use in_array() for search your array-needle
//in the $arraypush[0] where is the data, not in $arraypush only
if(in_array($foo_array, $arraypush[0]))
{
die($foo);
}
else
{
die("-");
}
Try this I think is help full to you.
<?php
$a = array (
0 => array (
0 => array ( 'planoption_id' => 1 ),
1 => array ( 'planoption_id' => 2 ),
2 => array ( 'planoption_id' => 3 ),
3 => array ( 'planoption_id' => 4 ),
4 => array ( 'planoption_id' => 5 ),
5 => array ( 'planoption_id' => 6 ),
6 => array ( 'planoption_id' => 7 ),
7 => array ( 'planoption_id' => 53 ),
8 => array ( 'planoption_id' => 1 ),
9 => array ( 'planoption_id' => 2 ),
)
);
function multi_in_array($value, $array)
{
foreach ($array AS $item)
{
if (!is_array($item))
{
if ($item == $value)
{
//return true;
echo "INCLUDED";
}
continue;
}
if (in_array($value, $item))
{
//return true;
echo "INCLUDED";
}
else if (multi_in_array($value, $item))
{
//return true;
echo "-";
}
}
//return false;
echo "-";
}
echo multi_in_array(2, $a);
Output:- -INCLUDED-------INCLUDED--
The following even works for arrays of arbitrary dimensions:
$found = false;
$needle = 2;
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach($it as $v) {
if ($v == $needle) {
$found = true;
break;
}
}
echo $found ? 'INCLUDED' : '-';

Sum of array for same values

I have this array:
Array (
[0] => Array (
[TaxeName] => TPS
[TaxeAmount] => 7
[Price] => 14
)
[1] => Array (
[TaxeName] => TVQ
[TaxeAmount] => 9.975
[Price] => 10
)
[2] => Array (
[TaxeName] => TVQ
[TaxeAmount] => 9.975
[Price] => 18
)
)
How I can get another array:
- Grouping the TaxeName and the TaxeAmount and
- Making the sum of the amount Price ?
Like this:
Array (
[0] => Array (
[TaxeName] => TPS
[TaxeAmount] => 7
[Price] => 14
)
[1] => Array (
[TaxeName] => TVQ
[TaxeAmount] => 9.975
[Price] => 28
)
)
It can be done with a nested foreach:
$original = array(.......); // your current array
$newArr = array();
foreach($original as $origVal){
$exists = false;
foreach($newArr as $key => $newVal){
if($newVal['TaxeName'] == $origVal['TaxeName']){
$newArr[$key]['Price'] += $origVal['Price'];
$exists = true;
break;
}
}
if(!$exists){
$newArr[] = $origVal;
}
}
Outputs
Array
(
[0] => Array
(
[TaxeName] => TPS
[TaxeAmount] => 7
[Price] => 14
)
[1] => Array
(
[TaxeName] => TVQ
[TaxeAmount] => 9.975
[Price] => 28
)
)
Something like this maybe:
$final = array();
foreach ($arr as $subarr)
{
if (!isset($final[$subarr['TaxeName']]))
{
$final[$subarr['TaxeName']] = array('Price' => 0);
}
$final[$subarr['TaxeName']]['TaxeName'] = $subarr['TaxeAmount'];
$final[$subarr['TaxeName']]['TaxeName'] = $subarr['TaxeName'];
$final[$subarr['TaxeName']]['Price'] = $final[$subarr['TaxeName']]['Price'] + $subarr['Price'];
}
The idea is to make a new array with the values that you need and initializing it with the price set to 0 so you can increment it in the foreach
You can do it like this also:
<?php
// Source
$myData = array(
array(
'TaxeName' => 'TPS',
'TaxeAmount' => 7,
'Price' => 14,
),
array(
'TaxeName' => 'TVQ',
'TaxeAmount' => 9.975,
'Price' => 10,
),
array(
'TaxeName' => 'TVQ',
'TaxeAmount' => 9.975,
'Price' => 18,
)
);
// Helper Function
function parseData($data)
{
$parsedData = array();
if (is_array($data)) {
foreach ($data as $dataItem) {
if (!array_key_exists($dataItem['TaxeName'], $parsedData)) {
$parsedData[$dataItem['TaxeName']] = array(
'TaxeName' => $dataItem['TaxeName'],
'TaxeAmount' => $dataItem['TaxeAmount'],
'Price' => floatval($dataItem['Price'])
);
} else {
$parsedData[$dataItem['TaxeName']]['Price'] += floatval($dataItem['Price']);
}
}
}
return array_values($parsedData);
}
// Test
$parsed_data = parseData($myData);
var_dump($parsed_data);
?>
Outputs:
Just use this function, input is your array, output is the array you required:
function calculate(array $input){
$output = [];
foreach ($input as $v){
if (array_key_exists($v['TaxeName'], $output)){
$output[$v['TaxeName']]['Price'] += $v['Price'];
} else {
$output[$v['TaxeName']] = $v;
}
}
return array_values($output);
}
I know that solutions with external classes are not welcome here on SO. I'm showing this just to illustrate the "Grouping the TaxeName and the TaxeAmount" task.
//use class tablearray from https://github.com/jspit-de/tableArray
$data = [
['TaxeName' => 'TPS', 'TaxeAmount' => 7, 'Price' => 14],
['TaxeName' => 'TVQ', 'TaxeAmount' => 9.975, 'Price' => 10],
['TaxeName' => 'TVQ', 'TaxeAmount' => 9.975, 'Price' => 18],
['TaxeName' => 'TVQ', 'TaxeAmount' => 19.975, 'Price' => 23]
];
$newData = tableArray::create($data)
->filterGroupSum('Price',['TaxeName','TaxeAmount'])
->fetchAll()
;
echo '<pre>';
var_export($newData);
Output:
array (
0 =>
array (
'TaxeName' => 'TPS',
'TaxeAmount' => 7,
'Price' => 14,
),
1 =>
array (
'TaxeName' => 'TVQ',
'TaxeAmount' => 9.975,
'Price' => 28,
),
2 =>
array (
'TaxeName' => 'TVQ',
'TaxeAmount' => 19.975,
'Price' => 23,
),
)

Removing items from an array based on items in another array

I have 2 arrays:
Array ( [0] => Array ( [intTrackId] => 41 [intAverageRating] => 10 [bolNewRelease] => 0 [dtDateAdded] => 2013-03-08 17:32:26 ) [1] => Array ( [intTrackId] => 1 [intAverageRating] => 7 [bolNewRelease] => 0 [dtDateAdded] => 2013-03-08 18:54:35 ))
Array ( [0] => Array ( [intTrackId] => 41 [intAverageRating] => 5.5000 [bolNewRelease] => 1 [dtDateAdded] => 2014-03-25T09:39:28Q ) [1] => Array ( [intTrackId] => 361 [intAverageRating] => 8.0000 [bolNewRelease] => 1 [dtDateAdded] => 2014-03-25T09:39:28Q ))
I want to remove the items in the second which have a matching track ID in the first. So in this example, I would get:
Array ( [0] => Array ( [intTrackId] => 361 [intAverageRating] => 8.0000 [bolNewRelease] => 1 [dtDateAdded] => 2014-03-25T09:39:28Q ))
Is this possible with array_filter or is this a little complex for that?
Just use array_udiff() - it's intended to do this:
$one = Array (
0 => Array ('intTrackId' => 41, 'intAverageRating' => 10, 'bolNewRelease' => 0, 'dtDateAdded' => '2013-03-08 17:32:26' ),
1 => Array ('intTrackId' => 1, 'intAverageRating' => 7, 'bolNewRelease' => 0, 'dtDateAdded' => '2013-03-08 18:54:35' )
);
$two = Array (
0 => Array ('intTrackId' => 41, 'intAverageRating' => 5.5000, 'bolNewRelease' => 1, 'dtDateAdded' => '2014-03-25T09:39:28Q' ),
1 => Array ('intTrackId' => 361, 'intAverageRating' => 8.0000, 'bolNewRelease' => 1, 'dtDateAdded' => '2014-03-25T09:39:28Q' )
);
$result = array_udiff($two, $one, function($x, $y)
{
return $x['intTrackId']-$y['intTrackId'];
});
Yes it can be done with array_filter:
$array1 = array(...);
$array2 = array(...);
$newArray = array_filter($array2, function($item) use ($array1){
foreach($array1 as $elem){
if($item['intTrackId'] == $elem['intTrackId']){
return false;
}
}
return true;
});
I would first create a loop and store all track IDs from the first array in a separate array.
Then I'd loop over the second array and delete those keys that exist in the track ID array.
$track_ids = array();
foreach($array1 as $index => $items) {
$track_ids[$items['intTrackId']] = $index;
}
foreach($array2 as $items) {
if (isset($track_ids[$items['intTrackId']])) {
unset($array2[$track_ids[$items['intTrackId']]]);
}
}

reformat multidimensional array based on value

i have an array in below format
$op = Array
(
[0] => Array
(
[0] => Array
(
[contact_id] => 36
[sender_id] => 79
[sendto] => 9192
)
[1] => Array
(
[event_id] => 145
[sender_id] => 9139
[sendto] => 9192
)
)
[1] => Array
(
[0] => Array
(
[event_id] => 145
[sender_id] => 9272
[sendto] => 9290
)
)
[2] => Array
(
[0] => Array
(
[event_id] => 145
[sender_id] => 9138
[sendto] => 9316
)
[1] => Array
(
[event_id] => 145
[sender_id] => 9283
[sendto] => 9316
)
)
)
i want to filter array in a way that resultant array's key should be different sendto values and all sender_id under that sendto shoud come under that array's key
Desired output
Array
(
[9192] => Array
(
[0] =>79
[1] =>9139
)
[9290] =>Array
(
[0]=>9272
)
[9316] =>Array
(
[0] =>9138
[1] =>9283
)
)
although i tried with below code
foreach ($op as $ok=>$ov)
{
if( array_key_exists($ov['sendto'],$mid))
$mid[$ov['sendto']][]=$ok;
else
$mid[$ov['sendto']]=$ok;
}
but this one display notice:Undefined index: sendto
please tell me where i m doing wrong?? i always stuck in such problem
Something like this:
<?php
//Test Array
$op = array(
array(
array(
'contact_id' => 36,
'sender_id' => 79,
'sendto' => 9192
),
array(
'contact_id' => 145,
'sender_id' => 9139,
'sendto' => 9192
)
),
array(
array(
'contact_id' => 145,
'sender_id' => 9272,
'sendto' => 9290
)
),
array(
array(
'contact_id' => 145,
'sender_id' => 9138,
'sendto' => 9316
),
array(
'contact_id' => 145,
'sender_id' => 9283,
'sendto' => 9316
)
),
);
//Switch array format
$new = array();
foreach($op as $element)
{
foreach($element as $entity)
{
if(!isset($new[$entity['sendto']]))
{
$new[$entity['sendto']] = array();
}
$new[$entity['sendto']][] = $entity['sender_id'];
}
}
//Debug the new array.
print_r($new);
Try:
$mid = array();
foreach($op as $tmp_array)
{
foreach($tmp_array as $message)
{
if (!isset($mid[$message['sendto']]))
$mid[$message['sendto']] = array();
$mid[$message['sendto']][] = $message['sender_id'];
}
}
You should go like this:
foreach ($op as $ok=>$ov)
{
if(!array_key_exists('sendto',$mid))
{
$mid[$ov['sendto']] = array();
}
$mid[$ov['sendto']][] = $ov['sender_id'];
}

Categories