transform array data using php - php

[original:protected] => Array
(
[user_id] => 65751
[social_id] =>
[parent_id] =>
[org_id] => 1
[type] => 3
[s_id] => 1
[role_id] => 0
[active] => 1
[name] => RX
[first_name] => JJ
[last_name] => DKL
[email] => first#testmail.com
[secondary_email] =>
[username] => cLvcyUr2
)
[1] => User Object
(
[user_id] => 82197
[social_id] =>
[parent_id] =>
[org_id] => 1
[type] => 2
[s_id] => 1
[role_id] => 0
[active] => 1
[name] => sec
[first_name] => XX
[last_name] => J3
[email] => first#testmail.com
[secondary_email] =>
[username] => VfTqXyvJ
)
How to transform the array data mean to keep only two email and username rest should remove
Array (
[0] => Array (
[email] => first#testmail.com
[username] => cLvcyUr2
)
[1] => Array (
[email] => first#testmail.com
[username] => VfTqXyvJ
)
)
How could this possible i do not to unset data one by one it should automatically unset and pick only two value

Did you try something like that :
$index = array_search('user_id', $array);
unset($array[$index]);
Do that for all key you want to remove.

$newArray = [];
foreach ($oldArray as $item) {
$arr = [];
$arr['email'] = $item->email;
$arr['username'] = $item->username;
$newArray[] = $arr;
}

Why not create an empty array and just copy the values you need? Trying to unset everything in your array is a lot of work and is not really maintainable, out of experience.
Note that your pasted code contains both an array and object, but your question is about an array only.
$newArray = [];
foreach ($oldArray as $item) {
$newArray[] = [
'email' => $item->email,
'username' => $item->username
]; // If $item is object
$newArray[] = [
'email' => $item['email'],
'username' => $item['username']
]; // If $item is array
}
var_dump($newArray);

Related

How To Merge/push array into one in php

code
$result = [];
foreach ($getAllAgent as $rkey => $rvalue) {
$found = -1;
for ($i = 0; $i < count($result); $i++) {
if ($result[$i]["brokerid"] == $rvalue["brokerid"]) {
$found = $i;
$result[$i]['get_agent_details'][] = $rvalue['get_agent_details']; //here to combine
break;
}
}
// if not found, create new
if ($found == -1) {
$result[] = $rvalue;
}
results
Array
(
[0] => Array
(
[id] => 2
[brokerid] => 2
[agentid] => 3
[addedby] => 1
[get_agent_details] => Array
(
[id] => 3
[name] => kenang
[ic] => 932132923
[phone] => 2313123
[0] => Array
(
[id] => 4
[name] => ivan
[ic] => 32992131
[phone] => 31231
)
)
)
)
I have one set of an array, and I loop it and restructure match the data based on ID. After that I will try to merge the same data into one array, I able add into one array. But it will not combine as one. The correct result should be as below.
[get_agent_details] => Array
(
[0] => Array(
[id] => 3
[name] => kenang
[ic] => 932132923
[phone] => 2313123
),
[1] => Array
(
[id] => 4
[name] => ivan
[ic] => 32992131
[phone] => 31231
)
)
Your problem is in this line:
$result[] = $rvalue;
Consider the case where you only have one item; this will result in:
Array
(
[0] => Array
(
[id] => 2
[brokerid] => 2
[agentid] => 3
[addedby] => 1
[get_agent_details] => Array
(
[id] => 1
[name] => Chesney Hawkes
[ic] => 932132923
[phone] => 2313123
)
)
)
But to be consistent, you need get_agent_details to be a list of items, that happens to have one entry:
Array
(
[0] => Array
(
[id] => 2
[brokerid] => 2
[agentid] => 3
[addedby] => 1
[get_agent_details] => Array
(
[0] => Array
(
[id] => 1
[name] => Chesney Hawkes
[ic] => 932132923
[phone] => 2313123
)
)
)
)
So you need to re-arrange your data, for instance by writing:
$rvalue['get_agent_details'] = [0 => $rvalue['get_agent_details']];
$result[] = $rvalue;
Then, since get_agent_details will already be a list when you encounter a second matching item, your existing code in the inner loop will do the right thing:
// Add an item to the list
$result[$i]['get_agent_details'][] = $rvalue['get_agent_details'];

PHP Compare Arrays and clear all key if one in a array is empty

I'm looking for a solution to compare multiplay arrays with each of them i want to unset in all arrays if one key is empty. So as a example if [keywords] is empty i want to unset in all arrays [keywords]. Here are my arrays that i print_r.
Array
(
[0] => Array
(
[id] => 1
[pid] => 3
[sorting] => 128
[tstamp] => 1503039725
[title] => test
[alias] => test-3
[author] => 1
[inColumn] => main
[keywords] =>
[showTeaser] =>
[teaserCssID] =>
[teaser] =>
[printable] =>
[customTpl] =>
[protected] =>
[groups] =>
[guests] =>
[cssID] =>
[space] =>
[published] => 1
[start] =>
[stop] =>
)
[1] => Array
(
[id] => 2
[pid] => 3
[sorting] => 256
[tstamp] => 1503045056
[title] => test 2
[alias] => test-2
[author] => 1
[inColumn] => main
[keywords] =>
[showTeaser] =>
[teaserCssID] => a:2:{i:0;s:0:"";i:1;s:0:"";}
[teaser] =>
[printable] =>
[customTpl] =>
[protected] =>
[groups] =>
[guests] =>
[cssID] => a:2:{i:0;s:0:"";i:1;s:0:"";}
[space] => a:2:{i:0;s:0:"";i:1;s:0:"";}
[published] => 1
[start] =>
[stop] =>
)
)
What i have tried so far is
print_r($arrResult);
foreach($arrResult as $Result)
{
foreach ($Result as $arrKey => $arrField)
{
if(!empty($arrField))
{
$arrAllowedField[$arrKey] = $arrKey;
}
}
}
That build a array that contains the key which has values. But the problem is, that it also add empty fields of a other array.
Thanks
// remove empty entries in each array
$ar = array_map('array_filter', $ar);
// find keys having not empty value at least in one array
$temp = array_intersect_key(...$ar);
// save only keys from temp array
foreach($ar as &$item) {
$item = array_intersect_key($item, $temp);
}
demo
It removes the all the empty values from the array
$arrResult = array_map('array_filter', $arrResult);
$arrResult = array_filter( $arrResult );
echo "<pre>";
print_r($arrResult);
Output
Array
(
[0] => Array
(
[id] => 1
[pid] => 3
[sorting] => 128
[tstamp] => 1503039725
[title] => test
[alias] => test-3
[author] => 1
[inColumn] => main
[published] => 1
)
)

Transpose associative array of indexed arrays to be indexed array of associative arrays [duplicate]

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 5 months ago.
I need to convert a PHP array that I'm getting from a form submission, so that I can use it more usefully in a db.
Array
(
[first_name] => Array
(
[0] => Ben
[1] => Tom
[2] => Sarah
)
[last_name] => Array
(
[0] => Wills
[1] => Main
[2] => Bliss
)
[email] => Array
(
[0] => ben.wills#argh.com
[1] => tommain#argh.com
[2] => sbliss#argh.com
)
)
to:
Array
(
[0] => Array
(
[first_name] => Ben
[last_name] => Wills
[email] => ben.wills#argh.com
)
[1] => Array
(
[first_name] => Tom
[last_name] => Main
[email] => tommain#argh.com
)
[2] => Array
(
[first_name] => Sarah
[last_name] => Bliss
[email] => sbliss#argh.com
)
)
How can I change the values' key paths so that the first level keys and the second level keys are swapped?
The solution using array_keys, array_values, array_map, call_user_func_array and array_combine functions:
$keys = array_keys($arr); // supposing $arr is your initial array
$data = call_user_func_array("array_map", array_merge([null], array_values($arr)));
$result = array_map(function($v) use($keys){
return array_combine($keys, $v);
}, $data);
print_r($result);
The output:
Array
(
[0] => Array
(
[first_name] => Ben
[last_name] => Wills
[email] => ben.wills#argh.com
)
[1] => Array
(
[first_name] => Tom
[last_name] => Main
[email] => tommain#argh.com
)
[2] => Array
(
[first_name] => Sarah
[last_name] => Bliss
[email] => sbliss#argh.com
)
)
Use the below code. Hope at least this gives some idea how to proceed :)
$array = array(
'first_name' => array('Ben','Tom','Sarah'),
'last_name' => array('Wills','Main','Bliss'),
'email' => array('ben.wills#argh.com','tommain#argh.com','sbliss#argh.com')
);
// loop the array
foreach($array as $key=>$value){
foreach($value as $k=>$v){
// use the first loop key here
$new_array[$k][$key] = $v;
}
}
print_r($new_array);
Out Put:
Array
(
[0] => Array
(
[first_name] => Ben
[last_name] => Wills
[email] => ben.wills#argh.com
)
[1] => Array
(
[first_name] => Tom
[last_name] => Main
[email] => tommain#argh.com
)
[2] => Array
(
[first_name] => Sarah
[last_name] => Bliss
[email] => sbliss#argh.com
)
)
Doing a transform while retaining the key names can be achieved quite easily using PHP's MultipleIterator
$data = array(
'first_name' => array(
0 => 'Ben',
1 => 'Tom',
2 => 'Sarah',
),
'last_name' => array(
0 => 'Wills',
1 => 'Main',
2 => 'Bliss',
),
'email' => array(
0 => 'ben.wills#argh.com',
1 => 'tommain#argh.com',
2 => 'sbliss#argh.com',
),
);
$mi = new MultipleIterator(MultipleIterator::MIT_NEED_ALL | MultipleIterator::MIT_KEYS_ASSOC);
foreach($data as $key => $column) {
$mi->attachIterator(new ArrayIterator($column), $key);
}
$newData = [];
foreach($mi as $row) {
$newData[] = $row;
}
var_dump($newData);
Demo

How do I remove one array from another in php?

I have the following arrays in PHP:
print_r($employees) =
Array
(
[0] => Array
(
[p_id] => T29083999
[name] => Robert Plaxo
)
[1] => Array
(
[p_id] => T29083388
[name] => Yvan Sergei
)
[2] => Array
(
[p_id] => T21083911
[name] => Rhonda Saunders
)
[3] => Array
(
[p_id] => H02910382
[name] => Miguel Mercado
)
)
then this array:
print_r($record) =
Array
(
[0] => Array
(
[c_id] => 1
[section] => 1061
[term] => 201631
[p_id] => T29083388
[c_date] => 2016-04-01 09:14:00
)
)
I want to remove the array element from $employees that matches the p_id of $record. Array $record may have multiple entries like the one shown. If so, any p_id in $record must be removed from $employees.
I tried:
foreach ($employees as $k => $e) {
foreach ($record as $r) {
if ($e['p_id']==$r['p_id']) {
echo "found it!";
// if I uncomment the next line, it crashes! (500 server error)
// unset $employees[$k];
}
}
}
I just want to remove any element from $employees that has any employee that matches any record in $record with that employee id.
You were almost there; just needed parens around your unset()
I also took the liberty to change some of your variable names as single character variable names bother me.
$employees[] = [
'p_id' => 'T29083999',
'name' => 'Robert Plaxo',
];
$employees[] = [
'p_id' => 'T29083388',
'name' => 'Yvan Sergei',
];
$employees[] = [
'p_id' => 'T21083911',
'name' => 'Rhonda Saunders',
];
$employees[] = [
'p_id' => 'H02910382',
'name' => 'Miguel Mercado',
];
$records[] = [
'c_id' => '1',
'section' => '1061',
'term' => '201631',
'p_id' => 'T29083388',
'c_date' => '2016-04-01 09:14:00',
];
foreach ($employees as $key => $employee) {
foreach ($records as $record) {
if ($employee['p_id'] == $record['p_id']) {
echo "found it!";
unset($employees[$key]);
}
}
}
echo "<pre>";
print_r($employees);
Outputs
found it!
Array
(
[0] => Array
(
[p_id] => T29083999
[name] => Robert Plaxo
)
[2] => Array
(
[p_id] => T21083911
[name] => Rhonda Saunders
)
[3] => Array
(
[p_id] => H02910382
[name] => Miguel Mercado
)
)
The short solution using array_column and array_filter functions. It will also fit your requirement "Array $record may have multiple entries":
$p_ids = array_column($record, "p_id");
$employees = array_filter($employees, function($v) use($p_ids){
return !in_array($v["p_id"], $p_ids);
});
print_r($employees);
The output:
Array
(
[0] => Array
(
[p_id] => T29083999
[name] => Robert Plaxo
)
[2] => Array
(
[p_id] => T21083911
[name] => Rhonda Saunders
)
[3] => Array
(
[p_id] => H02910382
[name] => Miguel Mercado
)
)

PHP Array re-arrange to Multi Dimensional

I have an array structure like this and wanted to Re-arrange it to the one below. Any suggestions for a faster/simple fix? I already did the addition of the dates. Thanks! :)
Input:
Array
(
[0] => Array
(
[user_id] => 255
[display_name] => Mark
[company_name] => Company_A
)
[1] => Array
(
[user_id] => 150
[display_name] => Paul
[company_name] => Company_A
)
[2] => Array
(
[user_id] => 25
[display_name] => Hulk
[company_name] => Company_B
)
[3] => Array
(
[user_id] => 50
[display_name] => Bob
[company_name] => Company_B
)
)
Output:
Array
(
[Company_A] => Array
(
[company_total_hours] => 20h 45m
[employees] => Array
(
[0] => Array
(
[user_id] => 255
[display_name] => Mark
)
[1] => Array
(
[user_id] => 150
[display_name] => Paul
)
)
)
[Company_B] => Array
(
[company_total_hours] => 7h 30m
[employees] => Array
(
[0] => Array
(
[user_id] => 25
[display_name] => Hulk
)
[1] => Array
(
[user_id] => 50
[display_name] => Bob
)
)
)
)
My Attempts:
<?php
$company_names = array();
foreach ($records as $k => $v) {
$company_names[] = $v->company_name;
}
$company_names = array_unique($company_names);
// hard coded testing
if (count($company_names) > 0) {
foreach($company_names as $k2 => $v2) {
$final_array[$v2]['company_total_hours'] = rand(1, 20);
$final_array[$v2]['employees'] = array(
array('user_id' => '255', 'display_name' => 'Mark'),
array('user_id' => '150', 'display_name' => 'Paul')
);
}
}
// on-going testing right now here....
I don't see where you derive your hours from so I left that out.
$i = 0;
foreach($vals as $keys => $arrays) {
if(!isset($new[$arrays['company_name']]))
$i = 0;
$new[$arrays['company_name']]['employees'][$i]['display_name'] = $arrays['display_name'];
$new[$arrays['company_name']]['employees'][$i]['user_id'] = $arrays['user_id'];
$i++;
}
Gives you:
Array
(
[Company_A] => Array
(
[employees] => Array
(
[0] => Array
(
[display_name] => Mark
[user_id] => 255
)
[1] => Array
(
[display_name] => Paul
[user_id] => 150
)
)
)
[Company_B] => Array
(
[employees] => Array
(
[0] => Array
(
[display_name] => Hulk
[user_id] => 25
)
[1] => Array
(
[display_name] => Bob
[user_id] => 50
)
)
)
)
foreach($arr as $v)
{
if(!$arr2[$v['company_name']]['employees'])
$arr2[$v['company_name']]['employees'] = array();
if(!$arr2[$v['company_name']]['company_total_hours'])
$arr2[$v['company_name']]['company_total_hours'] = '2h';//addional value
$arr2[$v['company_name']]['employees'][] = array('user_id'=>$v['user_id'],
'display_name'=>$v['display_name']
);
}
I have created a function which does the same thing as the answer given by #Rasclatt.
function groupByKeyValue($array, $oldKeyName, $newKeyName){
$newArray = array();
foreach($array as $key=>$value){
if(isset($newArray[$value[$oldKeyName]][$newKeyName])){
$newArray[$value[$oldKeyName]][$newKeyName][] = array('user_id'=> $value['user_id'], 'display_name' => $value['display_name']);
}else{
$newArray[$value[$oldKeyName]] = array($newKeyName => array(array('user_id'=> $value['user_id'], 'display_name' => $value['display_name'])));
}
}
return $newArray;
}
//usage
$newArray = groupByKeyValue($array, 'company_name', 'employees');
You can add a third parameter to send the keys for the array values which needs to be used in the new array for 'employees'. Please check this link for the working of the function http://goo.gl/I6Of5y

Categories