Removing selected elements from array of associative arrays - php

I have the following array of associative arrays.
$result = array(
(int) 0 => array(
'name' => 'Luke',
'id_number' => '1111',
'address' => '1544addr',
'time_here' => '2014-04-12 13:07:08'
),
(int) 1 => array(
'name' => 'Sam',
'id_number' => '2222',
'address' => '1584addr',
'time_here' => '2014-04-12 14:15:26'
I want to remove selected elements from this array such that it will look like this;
array(
(int) 0 => array(
'name' => 'Luke',
'id_number' => '1111'
),
(int) 1 => array(
'name' => 'Sam',
'id_number' => '2222',
This is the code I wrote;
foreach($result as $value)
{
unset($value('address') );
unset($value('time_here') );
}
When I run the code, Apache web server crashed.
Can the smarter members point out what did I do wrong? Thank you very much.

Array notation is wrong, use this;
$finalResult = array();
foreach($result as $value)
{
unset($value['address'] );
unset($value['time_here'] );
$finalResult[] = $value;
}
Here is a working demo: Demo

That is because you are not accessing array correctly. Use square bracket insted of round brackets :
foreach($result as $value)
{
unset($value['address'] );
unset($value['time_here'] );
}

Related

How to extract an array with multiple array keys and values to another array?

Please note that my php version is not 7.
I have an array of arrays like:
array(
'0' => array('id'=>1,'name'=>'abc',"class"=>'xyz'),
'1' => array('id'=>2,'name'=>'abc1',"class"=>'xyz1'),
'2' => array('id'=>3,'name'=>'abc',"class"=>'xyz2'),
);
I want to extract it into two arrays. like
array(
'0' => array('id'=>1,'name'=>'abc'),
'1' => array('id'=>2,'name'=>'abc1'),
'2' => array('id'=>3,'name'=>'abc'),
);
array(
'0' => array('id'=>1,"class"=>'xyz'),
'1' => array('id'=>2,"class"=>'xyz1'),
'2' => array('id'=>3,"class"=>'xyz2'),
);
How can i achieve this, I am in search of some built-in function etc, I studied its supported with array_column but with versions higher than 7.
Edit:
I also tried array_intersect_key and array_slice but its working with single dimensional array.
Then you might want to keep it simple and just use a straight forward foreach loop like this
$old = array(
array('id'=>1,'name'=>'abc',"class"=>'xyz'),
array('id'=>2,'name'=>'abc1',"class"=>'xyz1'),
array('id'=>3,'name'=>'abc',"class"=>'xyz2')
);
foreach ( $old as $temp ) {
$new1 = array('id' => $temp['id'], 'name' => $temp['name']);
$new2 = array('id' => $temp['id'], 'class' => $temp['class']);
}
Use a foreach and add the values to a new array for example:
$idsNames = [];
$idsClasses = [];
$items = [
array('id' => 1, 'name' => 'abc', "class" => 'xyz'),
array('id' => 2, 'name' => 'abc1', "class" => 'xyz1'),
array('id' => 3, 'name' => 'abc', "class" => 'xyz2'),
];
foreach ($items as $item) {
$idsNames[] = ["id" => $item["id"], "name" => $item["name"]];
$idsClasses[] = ["id" => $item["id"], "class" => $item["class"]];
}

Transform keys and values in an associative array

I have 2 associative Arrays but they are in the wrong form. The first
Array(
'name' => 'adam',
'age' => '13'
)
and the second one shoulb be combined (merged?)
Array(
'key' => 'pet',
'value' => 'dog'
)
that the result would be like
Array(
'name' => 'adam',
'age' => '13',
'pet' => 'dog'
)
Can anyone give me a hint/solution?
EDIT: I did it that way:
$result = array_merge($item, array_column($metas, 'v', 'k'));
Thanks
$data1 = Array(
'name' => 'adam',
'age' => '13'
);
$data2 = Array(
'key' => 'pet',
'value' => 'dog'
);
let $result=[];
foreach ($data1 as $key => $value) {
$result[$data2['key']]=$data2['value'];
$result=$data1+$result;
}
print_r($result);

php loop over multidimensional array can combine same key/value into new array element

I am getting some data out of mysql into an array like this
array(
[0] = array(
'code' => '123456',
'title' => 'something',
'price' => '2.00',
'other_value' => '555555'
),
[1] = array(
'code' => '123456',
'title' => 'something',
'price' => '2.00',
'other_value' => '666666'
),
[2] = array(
'code' => '234567',
'title' => 'something else',
'price' => '3.00',
'other_value' => '333333'
),
[3] = array(
'code' => '345678',
'title' => 'another thing',
'price' => '4.00',
'other_value' => NULL
),
)
what i need to do is for each row, if the key code appears more than once, merge the rows into one but create a new array for the other_value like so
array(
[0] = array(
'code' => '123456',
'title' => 'something',
'price' => '2.00',
'other_value' => array(
[0] => '555555',
[1] => '666666'
)
),
[1] = array(
'code' => '234567',
'title' => 'something else',
'price' => '3.00',
'other_value' => '333333'
),
[2] = array(
'code' => '345678',
'title' => 'another thing',
'price' => '4.00',
'other_value' => NULL
),
)
What is the best way to achieve this?
I did think about looping over the each row and checking for existence of thtat key/value then do something if it exists.
#AdRock i hope you want to merge array in case of when 'code' will be same, if this is so then try below one:
<?php
$arr = array(
array(
'code' => '123456',
'title' => 'something',
'price' => '2.00',
'other_value' => '555555'
),
array(
'code' => '123456',
'title' => 'something',
'price' => '2.00',
'other_value' => '666666'
),
array(
'code' => '234567',
'title' => 'something else',
'price' => '3.00',
'other_value' => '333333'
),
array(
'code' => '345678',
'title' => 'another thing',
'price' => '4.00',
'other_value' => NULL
)
);
echo "<pre>";
print_r($arr);// array before
$isExist = array();
foreach($arr as $key => $value){
if(in_array($value["code"], $isExist)){
$getKey = array_search($value["code"], $isExist);
$arr[$getKey]["other_value"] = array($arr[$getKey]["other_value"], $value["other_value"]);
unset($arr[$key]);
}
else{
$arr[$key] = $value;
}
$isExist[$key] = $value["code"];
}
echo "<pre>";
print_r(array_values($arr));// array after
?>
The approach that I would suggest is to loop through the array and store the value of code into a new array and store the entire result set into a new array. With each iteration, check whether the value is present or not in the code value stored array. And if value found then in that case, get the key of the code array and use the same key for the result array and store it inside the other_value. Hope it makes sense.
Looping over the array and creating a new array using the 'code' values as keys might be the simplest method. In that case you can check if the key allready exists.
$new_array=array();
foreach($array as $part){
$code_as_key = $part['code'];
//if code allready in the new array, just add a new value
if( isset($new_array[$code_as_key]) ){
$new_array[$code_as_key]['other_value'][] = $part['other_value'];
}
//else add the new code
else{
$new_array[$code_as_key]=$part;
}
}
//re-index the new array, starting from key 0
$new_array=array_values($new_array);

Merge two Arrays by Values

I have this Array:
$mergedItems = array(
0 => array(
'id_item' => 'AZ-110'
'amount' => 12
),
1 => array(
'id_item' => 'BZ-110',
'amount' => 13
),
2 => array(
'id_item' => 'BZ-210',
'amount' => 28
),
3 => array(
'id_item' => 'CZ-291',
'amount' => 11
)
);
AND this Array:
$items = array(
0 => array(
'number' => 'AZ-110'
),
1 => array(
'number' => 'BZ-110'
),
2 => array(
'number' => 'CZ-291'
),
3 => array(
'number' => 'BZ-210'
)
);
Now what i want is to order the first array by the id_item Value to match the same order than the 2nd one by its values.
The resulting array has to include all values of the 2nd array AND the belonging amount-value of the first array. The Keys must not be kept!
I can't use array_merge since the 2nd Array has a dynamic amount of more items, so i only want all items from the second Array that are set in the first one.
Does anyone get what i mean? I am searching for a quick and non-dirty way to get this result as expected.
/Edit:
Expected Array:
$detailedItems = array(
0 => array(
'number' => 'AZ-110',
'amount' => 12
),
1 => array(
'number' => 'BZ-110',
'amount' => 13
),
2 => array(
'number' => 'CZ-291',
'amount' => 11
),
3 => array(
'number' => 'BZ-210',
'amount' => 28
)
);
A PHP 5.5 solution:
$itemMap = array_flip(array_column($mergedItems, 'id_item'));
$result = array_map(
function($i) use($itemMap, $mergedItems) {
return $mergedItems[$itemMap[$i['number']]];
},
$items);
print_r($result);
For 5.3 <= PHP < 5.5 you can simply substitute array_map for array_column:
$itemMap = array_flip(array_map(
function($i) { return $i['id_item']; },
$mergedItems));
How it works
The idea is to create a map of item numbers to indexes inside $mergedItems, ie.
[
'AZ-100' => 0,
'BZ-110' => 1,
'BZ-210' => 2,
// etc
]
With this information at hand it's very easy to iterate over $items (so that the result will be ordered based on that array) and pick the appropriate element from $mergedItems to append to the result each time.
$temp = $items;
foreach($temp as &$val)
{
foreach($mergedItems as $item)
{
if($item['id_item'] == $val['number'])
{
$val['amount'] = $item['amount'];
break;
}
}
}
print_r($temp);
There isn't really a "non-dirty" (meaning single line) way to do this as far as I know, but this function should work:
$out = array();
foreach ($mergedItems as $key => $value) {
if (array_key_exists($key, $detailedItems)) { // Make sure it exists to prevent errors
$out[$key] = $detailedItems[$key] + array('amount' => $value['amount']);
} else {
$out[$key] = $value['amount'];
}
}
print_r($out);
You can try following codes:
foreach ($mergedItems as $item) {
$merged[$item['id_item']] = array('amount' => $item['amount']);
}
foreach ($items as $item)
{
$detailedItems[] = array_merge($item, $merged[$item['number']]);
}
Output
var_dump($detailedItems);
array (size=4)
0 =>
array (size=2)
'number' => string 'AZ-110' (length=6)
'amount' => int 12
1 =>
array (size=2)
'number' => string 'BZ-110' (length=6)
'amount' => int 13
2 =>
array (size=2)
'number' => string 'CZ-291' (length=6)
'amount' => int 11
3 =>
array (size=2)
'number' => string 'BZ-210' (length=6)
'amount' => int 28

php compare two multidimensional array and check for duplicate

I have two arrays
$array1 = array(
0 => array(
'user' => 'user0',
'id' => 'id0'
),
1 => array(
'user' => 'user1',
'id' => 'id1'
),
2 => array(
'user' => 'user2',
'id' => 'id2'
)
);
$array2 = array(
0 => array(
'emp' => 'emp0',
'id' => 'id3'
),
1 => array(
'emp' => 'emp1',
'id' => 'id1'
),
2 => array(
'emp' => 'emp2',
'id' => 'id2'
)
);
i need to loop array 2 first an d give input of id from array1 to the array 1 and search whether the value of id1 from arr1 exists in array2
Maybe this could work? (If I understood your question correctly)
$id_arr = array();
$final_arr = array();
checkArray($array1, $id_arr, $final_arr);
checkArray($array2, $id_arr, $final_arr);
function checkArray($arr, &$id_arr, &$final_arr) {
foreach ($arr as $key => $value) {
if (!in_array($value['id'], $id_arr)) {
$id_arr[] = $value['id'];
$final_arr[] = $value;
}
}
}
var_dump($final_arr);

Categories