How to combine array value with same key? - php

So i have this array that i get from query. The array look like this when i print_r
Array
(
[0] => Array
(
[Name] => NAME 1
[Last] => LastValue1
[Bid] =>
[Ask] =>
)
[1] => Array
(
[Name] => NAME 1
[Last] =>
[Bid] => BidValue1
[Ask] =>
)
[2] => Array
(
[Name] => Name 2
[Last] => LastValue2
[Bid] => BidValue2
[Ask] =>
)
[3] => Array
(
[Name] => NAME 1
[Last] =>
[Bid] =>
[Ask] => AskValue1
)
[4] => Array
(
[Name] =>Name 2
[Last] =>
[Bid] =>
[Ask] => AskValue2
)
)
and i want to achieve array looks like this
Array
(
[0] => Array
(
[Name] => NAME 1
[Last] => LastValue1
[Bid] => BidValue1
[Ask] => AskValue1
)
[2] => Array
(
[Name] => Name 2
[Last] => LastValue2
[Bid] => BidValue2
[Ask] => AskValue2
)
)
I try this way (get it from google)
$result = array();
foreach ($newArray as $element) {
$result[$element['Name']][] = $element;
}
echo "<pre>";print_r($result);
But it is not showing the result that i want. How can i achieve it ?
thanks in advance and sorry for my english

You can use below snippet for the same,
$result = [];
foreach ($newArray as $element) {
foreach ($element as $key => $value) {
// checking if value for key is already added to result array
if ((!empty($result[$element['Name']]) && !array_key_exists($key, $result[$element['Name']])) || empty($result[$element['Name']])) {
if (!empty($value)) { // checking if value not empty
$result[$element['Name']] = ($result[$element['Name']] ?? []);
// merge it to group wise name result array
$result[$element['Name']] = array_merge($result[$element['Name']], [$key => $value]);
}
}
}
}
array_merge — Merge one or more arrays
array_key_exists — Checks if the given key or index exists in the array
Demo
Output:-
Array
(
[0] => Array
(
[Name] => NAME1
[Last] => LastValue1
[Bid] => BidValue1
[Ask] => AskValue1
)
[1] => Array
(
[Name] => Name2
[Last] => LastValue2
[Bid] => BidValue2
[Ask] => AskValue2
)
)

Here is the shortest and simple solution by using foreach with array_filter
foreach($a as &$v){
$v = array_filter($v);
isset($r[$v['Name']]) ? ($r[$v['Name']] += $v) : ($r[$v['Name']] = $v);
}
You can use array_values to re arrange the order of array.
Working example : https://3v4l.org/XeQHa

Related

PHP delete array index through value

I'm trying to unset two specific array positions which contain two values.
My actual code to fill the array.
function get_store_list(){
$data = #file_get_contents('http://www.zwinky.com/xml/clothingList.xml');
$data = #simplexml_load_string($data);
$data = $data->xpath('//stores/store');
foreach($data as $store) {
$storeArray[] = array(
"name" => (string)$store['name'],
"id" => (string)$store['id']
);
}
return $storeArray;
}
$store = get_store_list();
The array looks like the following incase ill echo it out using print_r function:
Array
(
[0] => Array
(
[name] => Artizans
[id] => 20037336
)
[1] => Array
(
[name] => Bwabies!
[id] => 20080134
)
[2] => Array
(
[name] => Crave Mart
[id] => 20097365
)
[3] => Array
(
[name] => David & Goliath
[id] => 20099998
)
[4] => Array
(
[name] => Domo
[id] => 20098166
)
[5] => Array
(
[name] => Emily the Strange
[id] => 20101926
)
[6] => Array
(
[name] => Garfield
[id] => 20098167
)
[7] => Array
(
[name] => Jetsetter
[id] => 26
)
[8] => Array
(
[name] => Like Dat
[id] => 3
)
[9] => Array
(
[name] => Paris Hilton
[id] => 21
)
[10] => Array
(
[name] => Peppermint Place
[id] => 12
)
[11] => Array
(
[name] => Rocawear
[id] => 19
)
[12] => Array
(
[name] => ShoeBuy
[id] => 10
)
[13] => Array
(
[name] => Skelanimals
[id] => 20100198
)
[14] => Array
(
[name] => Snoop Dogg
[id] => 20
)
[15] => Array
(
[name] => SW&TH
[id] => 20096121
)
[16] => Array
(
[name] => The Castle
[id] => 1
)
[17] => Array
(
[name] => The Lair
[id] => 4
)
[18] => Array
(
[name] => The Mix
[id] => 923
)
[19] => Array
(
[name] => The Powerpuff Girls
[id] => 20098121
)
[20] => Array
(
[name] => The Surf Shop
[id] => 5
)
[21] => Array
(
[name] => Tie The Knot
[id] => 20076231
)
[22] => Array
(
[name] => tokidoki
[id] => 20099224
)
[23] => Array
(
[name] => University Club
[id] => 2
)
[24] => Array
(
[name] => Z Avenue
[id] => 6
)
[25] => Array
(
[name] => Z's Greetings
[id] => 20099506
)
)
Now $store does contain 2 array indexes which I have to delete. Which are the following ids: 21 and 20076231
I've been trying the following already:
Array search code without beeing success. Does anyone have a idea what I could try?
There are a handful different approaches for this simple issue. One of them could be using function array_filter():
/**
* #param array $list the list to process
* #param array $IDsToRemove the IDs of elements to remove from $list
* #return array a subset of $list that does not contain elements having 'id' in $IDsToRemove
*/
function removeFromArray(array $list, array $IDsToRemove)
{
return array_filter(
// Filter the input list...
$list,
// ... using a function...
function (array $item) use ($IDsToRemove) {
// ... that accepts an element if its "id" is not in $IDsToRemove
return ! in_array($item['id'], $IDsToRemove);
}
);
}
// Usage
$filteredStore = removeFromArray($store, array(21, 20076231));
Try this in your loop, this will not include in your array than no need to unset like this:
foreach($data as $store) {
if($store['id'] == '20076231')
continue;
$storeArray[] = array(
"name" => (string)$store['name'],
"id" => (string)$store['id']
);
}
If you need to unset an item from your array after it's been created, take a look at array_map.
First map your array to retrieve the index of each ID.
$map = array_map(function($item){ return $item['id']; }, $store);
Then get the index of your ID from the map (e.g. 21).
$index = array_search(21, $map);
Then remove with array_splice.
array_splice($store, $index, 1);
why not use directly the id in your $storeArray? And as it seems to be integer why do you force it to (string)?
Try this:
function get_store_list(){
$data = #file_get_contents('http://www.zwinky.com/xml/clothingList.xml');
$data = #simplexml_load_string($data);
$data = $data->xpath('//stores/store');
foreach($data as $store) {
$storeArray[(int)$store['id']] = array(
"name" => (string)$store['name']
);
}
return $storeArray;
}
// delete the keys you want
unset ($storeArray[21], $storeArray[20076231]);
// or if you have more ids to delete you can create a deleteArray
$deleteArray = array(2, 20076231);
foreach ($deleteArray as $toDelete){
unset($storeArray($toDelete);
}
One line code is cool but sometimes explicit code is preferable.
function filter_by_id(array $data, $id)
{
foreach ($data as $k => &$v) {
foreach ((array) $id as $i) {
if ($v['id'] === $i) {
$v = null;
}
}
}
// 'array_filter()' produces a new array without the null entries.
// 'array_values()' produces a new array with indexes without gaps.
return array_values(array_filter($data));
}
You can filter by one id at time
$store = filter_by_id($store, 21);
Or you can filter multiple ids at the same time:
$store = filter_by_id($store, [21, 20076231]);

PHP - Merge 2 arrays of object using a key/id

I want to merge the 2 arrays of objects based on the 'id' field of Array1 and the 'itemVendorCode' of Array2. I also wanted to remove from the resulting arrays of object anything that didn't match.
Array1:
Array
(
[0] => stdClass Object
(
[id] => 10-423-1176
[qty] => 2
[price] => 12.6
)
[1] => stdClass Object
(
[id] => 89-575-2354
[qty] => 24
[price] => 230.35
)
[2] => stdClass Object
(
[id] => 89-605-1250
[qty] => 2
[price] => 230.35
)
)
Array2:
Array
(
[0] => Item Object
(
[internalId] => 14062
[itemVendorCode] => 89-605-1250
)
[1] => Item Object
(
[internalId] => 33806
[itemVendorCode] => 89-575-2354
)
[2] => Item Object
(
[internalId] => 64126
[itemVendorCode] => 26-295-1006
)
)
I was able to solve this by this code:
$indexed = array();
foreach($itemsArray as $value) {
$indexed[$value->itemVendorCode] = $value;
}
$results = array();
foreach($vendorItems as $obj) {
$value = $indexed[$obj->id];
if (isset($value)) {
foreach($value as $name => $val) {
$obj->$name = $val;
array_push($results, $obj);
}
}
}
print_r($results);
credits to the original poster. I just modified it a bit,
I was able to get the result like this:
Array
(
[0] => stdClass Object
(
[id] => 10-423-1176
[qty] => 2
[price] => 12.6
[internalId] => 2035
[itemVendorCode] => 10-423-1176
)
[1] => stdClass Object
(
[id] => 10-423-1176
[qty] => 2
[price] => 12.6
[internalId] => 2035
[itemVendorCode] => 10-423-1176
)
[2] => stdClass Object
(
[id] => 14-102-1010
[qty] => 16
[price] => 3.2
[internalId] => 57033
[itemVendorCode] => 14-102-1010
)
)
I think you will have to use array_map function which provides you a callback function to execute on array(s).
In the callback function:
- declare your array1
- foreach the second array
- set an if statement to check that the current iteration with the id value matches the itemVendorCode of the array2 and return it
something like this:
// You have to specify to PHP to use a local copy of your $array2 to works with it into your callback
$cb = function ($obj1) use ($array2)
{
// you foreach this array
foreach ($array2 as $obj2) {
// if the value of id matches itemVendorCode
if ($obj1->id === $obj2->itemVendorCode) {
// you return the id
return $obj->id;
}
}
};
// this function will fill a new array with all returned data
$mergedArray = array_map($cb, $array1);
This code is a sample but doesn't provide you, your needled solution, try to update it to do what you exactly want ;)

How to combine or merge array in PHP

Could this be possible? How to combine or merge arrays in php. to fetch data individualy for echoing purpose. Could this be possible? How to combine or merge arrays in php. to fetch data individualy for echoing purpose.
Array(
[0] => stdClass Object
(
[id] => 1
[icd] => J96.0
[rank] => 1
[description] => Acute respiratory failure
)
[1] => stdClass Object
(
[id] => 1
[icd] => J44.1
[rank] => 2
[description] => Chronic obstructive pulmonary disease with (acute) exacerbation
)
[2] => stdClass Object
(
[id] => 1
[icd] => J18.9
[rank] => 3
[description] => Pneumonia, unspecified organism
)
)
To this
Array(
[id] => 1
[icd] => (
[0] => J96.0
[1] => J44.1
[2] => J18.9
)
[description] => (
[0] => Acute respiratory failure
[1] => Chronic obstructive pulmonary disease with (acute) exacerbation
[2] => Pneumonia, unspecified organism
)
)
USe This
array_merge_recursive
Follow Link
Link With Example
$new_array = array();
foreach($your_array as $row){
$new_array['id'] = $row->id;
$new_array['icd'][] = $row->icd;
$new_array['description'][] = $row->description;
}
print_r($new_array);
$output = array();
$arrayAB = array_merge($arrayA, $arrayB);
foreach ( $arrayAB as $value ) {
$keys = array("id", "icd", "rank", "description");
foreach ($keys as $key) {
$currKey = $value[$key];
if ( !isset($output[$currKey]) ) {
$output[$currKey] = array();
}
$output[$currKey] = array_merge($output[$currKey], $value);
}
}
var_dump($output);

php add some value on specific location in multidimensional array

I have array like this
Array ([0] => Array ( [user_id] => 21 [email] => momod#modara.com [brand] => Array ( [0] => GOFUEL_W [1] => GOFUEL_USD_W ) ) [1] => Array ( [user_id] => 22 [email] => hemisphere#modara.com [brand] => Array ( [0] => GOFUEL_W ) ) [2] => Array ( [user_id] => 23 [email] => madoka#modara.com [brand] => Array ( [0] => GOFUEL_W [1] => GOFUEL_USD_W [2] => GOFUEL_BGD_W ) ) )
i want to locate user_id 22 and put this value "GO_FUEL_SGD_W" on brand, what should i do, so the view of array will look like this
Array ([0] => Array ( [user_id] => 21 [email] => momod#modara.com [brand] => Array ( [0] => GOFUEL_W [1] => GOFUEL_USD_W ) ) [1] => Array ( [user_id] => 22 [email] => hemisphere#modara.com [brand] => Array ( [0] => GOFUEL_W => [1] =>GO_FUEL_SGD_W ) ) [2] => Array ( [user_id] => 23 [email] => madoka#modara.com [brand] => Array ( [0] => GOFUEL_W [1] => GOFUEL_USD_W [2] => GOFUEL_BGD_W ) ) )
Just use loop:
foreach($array as &$item)
{
if(array_key_exists('user_id', $item) &&
$item['user_id']==22 &&
array_key_exists('brand', $item) &&
!in_array('GO_FUEL_SGD_W', $item['brand']))
{
$item['brand'][] = 'GO_FUEL_SGD_W';
}
}
A simple foreach loop will do the job:
foreach($myarray AS &$subarray) {
if($subarray['user_id'] == 22) {
$subarray['brand'][] = "GO_FUEL_SGD_W";
break;
}
}
Working example: http://3v4l.org/8aQMj
You will need to iterate over the array and look for the element you're searching for.
foreach ($array as &$element) {
if ($element['user_id'] != 22)
continue;
$element['brand'][] = "GO_FUEL_SGD_W";
break;
}
With continue; all elements will be skipped, who have $element['user_id'] != 22 (and so none of the code after the continue; will be applied to them!).
Also it will end the loop once the requested element is reached and modified, thanks to break;.
$array= //your array;
foreach($array as $x){
if($x['user_id']=='22'){
$x['brand'][]='GO_FUEL_SGD_W';
break;
}
}

PHP foreach to get array keys and values

I think this is a tough one! Experts only?
Ok, I have some variables (returned from get_defined_vars):
Array
(
[lead] => Array
(
[2] => fstory
[4] => him
[5] => trtr
[1] => 508b38ee02f502.23680245.png
)
[form] => Array
(
[id] => 3
)
[fields] => Array
(
[0] => Array
(
[adminLabel] => formname
[id] => 2
)
[1] => Array
(
[adminLabel] => hisher
[id] => 4
[2] => Array
(
[adminLabel] => fname
[id] => 5
)
[3] => Array
(
[adminLabel] => sign
[id] => 1
)
)
I need to get the array fields key to be the [fields] [adminLabel] and the value to be the [lead] [#].
So in this example the array would have key=value
formname = fstory
fname = trtr
hisher = his
sign = 508b38ee02f502.23680245.png
Make any sense? Possible?
Try this. It is untested.
$result_values = $array['lead'];
$results = array();
foreach ($array['form']['fields'] as $value) {
if (is_array($value)) {
$results[$value['adminLabel']] = $result_values[$value['id']];
}
}
print_r($results);

Categories