array_push to a multidimensional array if array_key_exists - php

I am creating a new array ($Parts) from an existing array ($newarray), and reordering the array. However if the array key exists in the new array, I want to append to the 'location' and 'qty' arrays.
Here is what the new array structure looks like:
'4117-0171-249' =>
'pri_id' => '859'
'vendor' => 'R01298'
'score' => '0.00'
'location' =>
0 => '10103'
'qty' =>
0 => '70'
Here is my code I am using.
$Parts = array();
foreach($newarray AS $Ke => $Va) {
if(array_key_exists($Va['part_number'], $Parts)){
array_push($Parts[$location][],$Va['location']);
} else {
$Parts[$Va['part_number']] = array('pri_id' => $Va['pri_id'],
'vendor' => $Va['vendor'],
'score' => $Va['Score'],
'location' => array($Va['location']),
'qty' => array($Va['qty']),
);
}
}

If anyone stumbles across this in the future, the answer was this:
$Parts[$Va['part_number']]['location'][] = $Va['location'];

Related

Writing a HTML string content with array values in Laravel Controller

What I'm trying to accomplish is to write a html string in a controller with array values being looped in it. So for example;
$content = "Your store, at location A, has these items added to them". add array loop here. "Do take note!";
My array would be as such
array (
0 =>
array (
'id' => '5db29b6d31c391731239bbdf',
'name' => 'Diamond bracelet (sample)',
'tags' =>
array (
0 => 'female',
1 => 'jewelry',
),
'category' => 'Accessories',
'sku' => '1029EHW',
'priceType' => 'Fixed',
'unitPrice' => 190,
'cost' => 90,
'trackStockLevel' => true,
'isParentProduct' => false,
),
1 =>
array (
'id' => '5db29b6d31c391731239bbdb',
'name' => 'Long-sleeved shirt(sample)(M)',
'tags' =>
array (
0 => 'tops',
1 => 'cotton',
),
'category' => 'Women\'s Apparel',
'sku' => 'ABC1234-M',
'priceType' => 'Fixed',
'unitPrice' => 47.170000000000002,
'cost' => 20,
'trackStockLevel' => true,
'isParentProduct' => false,
'parentProductId' => '5db29b6d31c391731239bbd4',
'variationValues' =>
array (
0 =>
array (
'variantGroupId' => '5db29b6d31c391731239bbd5',
'value' => 'M',
),
),
),
)
note that the array can have many instances of product_name and sku, or can have none.
How do i populate this in my string to be like;
$content = "Your store, at location A, has these items added to them, 1) asd, 2)def, 3)asf . Do take note!
Try this, I've used \sprintf for ease, check if the output serves your purpose.
<?php
function stringMethod(): string
{
$count = 0;
$arrayString = [];
$array = [['product_name' => 'abc', 'product_sku' => 'def'],['product_name' => 'abc', 'product_sku' => 'asd']];
foreach ($array as $value){
$count++;
$arrayString[] = sprintf('%s)%s', $count, $value['product_sku']);
}
$string = \implode(',', $arrayString);
return \sprintf("Your store, at location A, has these items added to them %s Do take note!", $string);
}
echo stringMethod();
Hope this will help you. try to do it in less number of lines
$content = "Your store, at location A, has these items added to them, ";
$productArray = array (0 => array ('id' => '5db29b6d31c391731239bbdf','name' => 'Diamond bracelet (sample)','tags' => array (0 => 'female',1 => 'jewelry',),'category' => 'Accessories','sku' => '1029EHW','priceType' => 'Fixed','unitPrice' => 190,'cost' => 90,'trackStockLevel' => true,'isParentProduct' => false,),1 => array ('id' => '5db29b6d31c391731239bbdb','name' => 'Long-sleeved shirt(sample)(M)','tags' => array (0 => 'tops',1 => 'cotton',),'category' => 'Women\'s Apparel','sku' => 'ABC1234-M','priceType' => 'Fixed','unitPrice' => 47.170000000000002,'cost' => 20,'trackStockLevel' => true,'isParentProduct' => false,'parentProductId' => '5db29b6d31c391731239bbd4','variationValues' => array (0 => array ('variantGroupId' => '5db29b6d31c391731239bbd5','value' => 'M'))));
foreach ($productArray as $key => $product) {
$content .= ($key+1).') '.$product['name'];
if (count($productArray)-1!=$key) {
$content .= ', ';
}
}
$content .= ". Do take note!";
$content = "Your store, at location A, has these items added to them,". $this->getItemList($collection) .". Do take note!"
# Somewhere else in the controller
protected function getItemList(Collection $collection): string
{
return $collection->pluck('name')
->merge($collection->pluck('sku'))
->map(function($item, $key) {
return ($key + 1) . ') ' . $item;
})
->implode(', ');
}
An easy solution would be
$content = "Your store, at location A, has these items added to them";
$array = array(0=>["product_name" => "abc", "product_sku" => "def"], 1=>['product_name' => 'kdkf', 'product_sku'=> 'ljbkj']);
for($i = 0; $i<count($array); $i++){
$content .= ($i+1).") ".$array[$i]['product_name].' '.$array[$i]['product_sku'].', ';
}
$content .= "Do take note.";
This way you're just constantly concatonating the string value in separate parts instead of trying to inject it in the middle of the parent string.
not tested, may be syntax errors

unable to delete array key from multidimensional array in cakephp

I want to delete array index which contain rating 0 here is my array
array(
(int) 0 => array(
'Gig' => array(
'id' => '1',
'rating' => (int) 5
)
),
(int) 1 => array(
'Gig' => array(
'id' => '3',
'rating' => (int) 9
)
),
(int) 2 => array(
'Gig' => array(
'id' => '4',
'rating' => '0'
)
)
)
and what I did
for($i = 0; $i<count($agetGigsItem); $i++)
{
if($agetGigsItem[$i]['Gig']['rating']==0)
{
unset($agetGigsItem[$i]);
}
$this->set('agetGigsItem', $agetGigsItem);
}
i also try foreach loop but unable to resolve this issue.
foreach ($agetGigsItem as $key => $value) {
if ($value["Gig"]["rating"] == 0) { unset($agetGigsItem[$key]); }
}
I think you need to reupdate your array.
foreach ($agetGigsItem as $key => $value) {
if ($value["Gig"]["rating"] != 0)
{
unset($agetGigsItem[$key]);
}
$this->set('agetGigsItem', $agetGigsItem);
}
I hope you are missing $this and so you cannot access the array in CakePHP.
So try this:
foreach ($this->$agetGigsItem as $key => $value) {
if ($value["Gig"]["rating"] == 0) {
unset($this->$agetGigsItem[$key]);
}
}
This code will unset arrey index with value 0.
<?php
$array=array(
array(
'Gig' => array(
'id' => '1',
'rating' =>5
)
),
array(
'Gig' => array(
'id' => '3',
'rating' =>9
)
),
array(
'Gig' => array(
'id' => '4',
'rating' =>0
)
)
);
foreach($array as $a){
if($a['Gig']['rating']==0){
unset($a['Gig']['rating']);
}
$array1[]=$a;
}
var_dump($array1);
Destroying occurances within an array you are actually processing over with a for or a foreach is always a bad idea. Each time you destroy an occurance the loop can easily get corrupted and get in a terrible mess.
If you want to remove items from an array it is better to create a copy of the array and process over that new array in the loop but remove the items from the original array.
So try this instead
$tmparray = $this->agetGigsItem; // will copy agetGigsItem into new array
foreach ($tmparray as $key => $value) {
if ($value["Gig"]["rating"] == 0) {
unset($this->agetGigsItem[$key]);
}
}
unset($tmparray);

Switching two keys of an array

I feel like I am so close to successfully switching Jim and Jill in this associative array. I ALSO would like it to be repeatable, so if 'Joe' is added to the end, it will also swap 'Jim' and 'Joe.' Any pointers?
<?php
function jim_is_jill($their_name) {
$first = key($their_name);
foreach ($their_name as $key => $value) {
$lastmaybe = $key;
}
$lastmaybe = $these; // Lastmaybe is Jill
$these = $first;
return $their_name;
}
$their_name = array(
// Key => Value
'Jim' => 'dad',
'Josh' => 'son',
'Jamie' => 'mom',
'Jane' => 'daughter',
'Jill' => 'daughter'
);
print_r(jim_is_jill($their_name));
?>
CURRENT OUTPUT:
Array
(
[Jim] => dad
[Josh] => son
[Jamie] => mom
[Jane] => daughter
[Jill] => daughter
)
DESIRED OUTPUT:
Array
(
[Jill] => dad
[Josh] => son
[Jamie] => mom
[Jane] => daughter
[Jim] => daughter
)
Considering the array
$their_name = array(
// Key => Value
'Jim' => 'dad',
'Josh' => 'son',
'Jamie' => 'mom',
'Jane' => 'daughter',
'Jill' => 'daughter'
);
This function will produce :
function array_swap_values($array, $key1, $key2) {
$temp = $array[$key1];
$array[$key1] = $array[$key2];
$array[$key2] = $temp;
return $array;
}
$their_name = array_swap_values($their_name, 'Jim', 'Jill');
// -> array(
// 'Jim' => 'daughter',
// 'Josh' => 'son',
// 'Jamie' => 'mom',
// 'Jane' => 'daughter',
// 'Jill' => 'dad'
// );
Or this function will produce
function array_swap_keys($array, $key1, $key2) {
$ret = array();
foreach ($array as $key => $value) {
if ($key === $key1) {
$ret[$key2] = $array[$key2];
} else if ($key === $key2) {
$ret[$key1] = $array[$key1];
} else {
$ret[$key] = $value;
}
}
return $ret;
}
$their_name = array_swap_keys($their_name, 'Jim', 'Jill');
// -> array(
// 'Jill' => 'daughter',
// 'Josh' => 'son',
// 'Jamie' => 'mom',
// 'Jane' => 'daughter',
// 'Jim' => 'dad'
// );
** Update **
After your last edit, I modified the last function to return what is expected. It is pretty close to the first function, but it preserve the key ordering :
function array_swap_key_value($array, $key1, $key2) {
$ret = array();
foreach ($array as $key => $value) {
if ($key === $key1) {
$ret[$key2] = $array[$key1];
} else if ($key === $key2) {
$ret[$key1] = $array[$key2];
} else {
$ret[$key] = $value;
}
}
return $ret;
}
$their_name = array_swap_key_value($their_name, 'Jim', 'Jill');
// -> array(
// 'Jill' => 'dad',
// 'Josh' => 'son',
// 'Jamie' => 'mom',
// 'Jane' => 'daughter',
// 'Jim' => 'daughter'
// );
First thing, in my experience, it's not wise to rely on the order of an array, if it is not indexed by numbers. There are no tools (correct me if I'm wrong) to switch positions of keys or change keys themselves. It would have to be ugly hack. The only way to rename a key is to remove it and put it back correctly. But that disturbs the order of an array. You'll really have to rebuild the array from scratch, that's an easiest way, as suggested by Yanick, if you really want to do what you want to do. But there's more neat solution. You can make an array with numbered indexes, which you-shall-not-touch. That way, it will stay order. Then put simple small array in each value:
array('name'=> 'Jill, 'relationship'=>'daughter);
That way, you have full control of the order of indexes (thanks to numbered indexes) and you will only have to swap values, which is dead easy.
Or, you can omit those words and give it just numbered indexes everywhere. That way you'll write less but you will have to remember which is which:
array('jill', 'daughter');
is effectively same as:
array(0 => 'Jill', 1 => 'daughter');
So here's the code..
<?php
function swap_first_and_last($their_name) {
//get first and last keys
reset($their_name); // resets the array pointer to beginning
$k_first=key($their_name); // first key
end($their_name);
$k_last=key($their_name); // last key
// swap first and last:
$swap = $their_name[$k_first]['name'];
$their_name[$k_first]['name']=$their_name[$k_last]['name'];
$their_name[$k_last]['name']=$swap;
// note: you can use [0] and [1], if you modify your array that way
return $their_name;
}
// modified array
$their_name = array(
// note, you can omit those 0 => , 1 => ,2,... keys
0 => array('name' => 'Jim', 'relationship' => 'dad'),
1 => array('name' => 'Josh', 'relationship' => 'son'),
2 => array('name' => 'Jamie', 'relationship' => 'mom'),
3 => array('name' => 'Jane', 'relationship' => 'daughter'),
4 => array('name' => 'Jill', 'relationship' => 'daughter')
);
var_dump(swap_first_and_last($their_name));
And the result is:
array (size=5)
0 =>
array (size=2)
'name' => string 'Jill' (length=4)
'relationship' => string 'dad' (length=3)
1 =>
array (size=2)
'name' => string 'Josh' (length=4)
'relationship' => string 'son' (length=3)
2 =>
array (size=2)
'name' => string 'Jamie' (length=5)
'relationship' => string 'mom' (length=3)
3 =>
array (size=2)
'name' => string 'Jane' (length=4)
'relationship' => string 'daughter' (length=8)
4 =>
array (size=2)
'name' => string 'Jim' (length=3)
'relationship' => string 'daughter' (length=8)

multidimensional array - adding a key and value where a key and value is matched

I'm trying to add a key and value (associative) from an array to another array, where one specific key and value match. Here are the two arrays:
$array1 = array(
1 => array(
'walgreens' => 'location',
'apples' => 'product1',
'oranges' => 'product2'
),
2 => array(
'walmart' => 'location',
'apples' => 'product1',
'oranges' => 'product2',
'milk' => 'product3'
)
);
$array2 = array(
1 => array(
'walgreens' => 'location',
'apples' => 'product1',
'oranges' => 'product2',
'bananas' => 'product3',
)
);
Here is the attempt I made at modifying $array1 to have key 'bananas' and value 'product3':
$dataCJ = getCJItem($isbn);
foreach ($array1 as $subKey => $subArray) {
foreach($subArray as $dkey => $dval){
foreach($array2 as $cjk => $cjv){
foreach($cjv as $cjkey => $cjval){
if($dval['walgreens'] == $cjval['walgreens']){
$dval['bananas'] = $cjval['bananas'];
}
}
}
}
}
This doesn't work. How can I fix this?
Change => $dval to => &$dval. Currently you are creating and writing to a new variable and the update will not work in-place.
I would look at array_merge() function!
Here is a start with the PHP doc.
For your specific case, you could do the following :
foreach($array1 as $key1 => $values1){
foreach($array2 as $key2 => $values2){
if($values1[0] == $values2[0]){
$array1[$key1] = array_merge($values1, $values2);
}
}
}
Note to simplify the problem you should inverse the first key=> value pair of the array.
Having an array this way would be a lot simper :
array(
'location' => "The location (eg:walgreens)",
//...
);
This way you could change the comparison to the following instead :
$values1['location'] == $values2['location']
Which would be safer in the case the array is not built with the location as the first pair.

Processing data from query

I'm writing a 'get' function in a model class in codeigniter, but I need to process some of the data as it's returned, ideally without a whole bunch of overhead.
function get_answers($p)
{
$result = $this->db->get_where('answer', array('a_upid_fk' => $p))->result();
// foreach ($result->answer as $ans) {
// $result->answers = explode( '|', $ans, -1 );
// }
return $result;
}
The results look like this:
array (
0 =>
stdClass::__set_state(array(
'aid' => '742',
'a_upid_fk' => '231',
'answer' => '4555|||',
'a_qid_fk' => '70',
'created' => '2012-04-20 15:35:38',
'last_modified' => '2012-04-20 15:36:11',
'revision' => '1',
)),
1 =>
stdClass::__set_state(array(
'aid' => '743',
'a_upid_fk' => '231',
'answer' => NULL,
'a_qid_fk' => '71',
'created' => '2012-04-20 15:35:38',
'last_modified' => '2012-04-20 15:35:38',
'revision' => '1',
)) ...
the problem is the answer is stored as a pipe delimited list of answers, but I want the function to return it as an exploded array instead. I'm not sure of the syntax and how to create and replace or append the array to the array of objects I've pasted above.
You can see some code I've been trying commented out.
Ideally instead of 'answer' => '4555|||',
I would like to have
'answer' => array (
0 => '4555',
1=> '',
2=> '')
I have no problem making the array using explode but I'm not sure how to modify the original codeigniter active-record result.
Loop thru your sub-arrays:
$answer_array = explode('|', $answer);
foreach ($aswer_array as $instance)
{
$result[] = $instance;
}
Define __set_state()), call it using - $subarray = $result[0][$object->answer].

Categories