I need to create an array out of two arrays. I tried to use array_merge but it doesn't work.
With the first array, I pull all IDS of custom posts.
$all_posts = get_posts(array(
'fields' => 'id',
'posts_per_page' => -1,
'post_type' => 'items'
));
$ids = array();
foreach($all_posts as $a){
$id[] = array("id"=>$a->ID);
}
With second array I get only items assigned to that page:
$items = get_field('items');
$assigned_items= array();
foreach($items as $p){
$id = $p["select_item"][0]->ID;
$price= $p["price"];
$live = $p["live"];
$assigned_items[]=array("id"=>$id, "price"=>$available, "live"=>$live);
}
$price and $live variables are boolean.
Now I need to create an array out of these two. As the first array pulls all items, I need to merge with id in the second array. $price and $live could be one true one false.
I need to create an array with all ids from $ids array and add $price and $live elements to it from the second array if the ids are the same. If id doesn't exist in the second array, both price and live are false in the final output.
You need something like this, I also made some improvement to your code and check if there is any post or item before loop (to avoiding warning from php) also better error handling.
<?php
$ids = $assigned_items = $merged = array();
$all_posts = get_posts(array(
'fields' => 'id',
'posts_per_page' => -1,
'po|st_type' => 'items'
));
if($all_posts) {
foreach($all_posts as $a){
// $id[] = array("id"=>$a->ID);
$merged[$a->ID]["id"] = $a->ID;
}
$items = get_field('items');
if($items) {
foreach($items as $p){
$id = $p["select_item"][0]->ID;
$price= $p["price"];
$live = $p["live"];
// $assigned_items[]=array("id"=>$id, "price"=>$available, "live"=>$live);
$merged[$id]["price"] = $price;
$merged[$id]["live"] = $live;
} else {
// no item ...
}
}
} else {
// no post ...
}
if you assign your second iteration object, to the key in the array, you can easily merge them.
$assigned_items[$p["select_item"][0]->ID] = ['id' => $id, 'price' => $available, 'live' => $live];
Now you could join them, by accessing the assigned items by the id. Combining the arrays with the + operator.
foreach ($all_posts as $post) {
$combined = (array) $post + $assigned_items[$poost->ID] ?? [];
}
This would also eliminate you, from doing the $ids iteration.
Related
Here is My codes,
My question is if $company_id from foreach one equal to $Company_id from foreach two then echo company_name.
$ids = array();
$x = array();
$a = array();
foreach($companieslist as $keys=>$company) {
$x[$company->company_id] = [
'id' => $company->company_id,
'name' => $company->company_name
];
}
$entry = $a[$id];
foreach($uploads as $keys=>$general){
$ids[] = $general->Contract_Id;
$c_id = $general->Company_id;
....
Just talking from the performance side, what you should do is extract the company ids from the second batch to an array first, like this
$companies = array();
foreach ( $uploads as $keys => $general ) {
array_push( $companies, $general->Company_id );
}
Now, in the first foreach loop, you can just check if the company id exists in this $companies array, and then decide what to do
foreach($companieslist as $keys=>$company){
if(in_array($company->company_id,$companies)){
echo "Found {$company->company_id}<br/>\n";
}
}
I have an array which has different items example shirts, shoes, ties, jackets etc. And each of these items can have multiple designs denoted by their ids.
$variations = array(
'shirts' => array('2'),
'shoes' => array('7', '3'),
'jackets' => array('1', '5')
);
Now we are looking for an efficient way to create different variations of all of these.
## Required result ##
$result = array(
array('2','7','1'),
array('2', '7', '5'),
array('2','3','1'),
array('2','3','5')
);
Any help would be appreciated :)
EDIT: Our current function
function cartesian($input) {
$result = array();
while (list($key, $values) = each($input)) {
// If a sub-array is empty, it doesn't affect the cartesian product
if (empty($values)) {
continue;
}
// Seeding the product array with the values from the first sub-array
if (empty($result)) {
foreach($values as $value) {
$result[] = array($key => $value);
}
}
else {
// Second and subsequent input sub-arrays work like this:
// 1. In each existing array inside $product, add an item with
// key == $key and value == first item in input sub-array
// 2. Then, for each remaining item in current input sub-array,
// add a copy of each existing array inside $product with
// key == $key and value == first item of input sub-array
// Store all items to be added to $product here; adding them
// inside the foreach will result in an infinite loop
$append = array();
foreach($result as &$product) {
// Do step 1 above. array_shift is not the most efficient, but
// it allows us to iterate over the rest of the items with a
// simple foreach, making the code short and easy to read.
$product[$key] = array_shift($values);
// $product is by reference (that's why the key we added above
// will appear in the end result), so make a copy of it here
$copy = $product;
// Do step 2 above.
foreach($values as $item) {
$copy[$key] = $item;
$append[] = $copy;
}
// Undo the side effecst of array_shift
array_unshift($values, $product[$key]);
}
// Out of the foreach, we can add to $results now
$result = array_merge($result, $append);
}
}
return $result;
}
While I agree with comments beneath your question I implemented generator-based solution for fun so I can share it anyway:
$variations = array(
'shirts' => array('2'),
'shoes' => array('7', '3'),
'jackets' => array('1', '5')
);
var_dump(iterator_to_array(cartesian($variations), false));
function cartesian($lists, $product = [])
{
if (empty($product)) {
// first run, reverse array for array_pop and remove empty lists
$lists = array_reverse(array_filter($lists, 'count'));
}
$curr = array_pop($lists);
foreach ($curr as $c) {
if (empty($lists)) {
yield array_merge($product, [$c]);
} else {
yield from cartesian($lists, array_merge($product, [$c]));
}
}
}
This is how I did it
$parameters = array(
'shirts' => array('2'),
'shoes' => array('7', '3'),
'jackets' => array('1', '5')
);
$arPhrases = $parameters[0];
for ($i = 1; $i < count($parameters); $i++) {
$notFullCount = count($arPhrases);
foreach ($arPhrases as $phrase) {
foreach ($parameters[$i] as $newPart) {
$arPhrases[] = $phrase." ".$newPart;
}
}
$arPhrases = array_slice($arPhrases, $notFullCount);
}
I have below two arrays,
$category = array('available', 'notavailable' );
$values = array(1, 2 );
Now i want to get JSON output as below,
[{category: 'available', value:1}{category: 'notavailable', value:2}]
I tried using array_merge array_combine but could not got desired outlut with new Key values category and value,
How can i get that?
Thanks,
You can use array_map, if you have fixed keys:
<?php
$category = array('available', 'notavailable' );
$values = array(1, 2 );
$array = array_map(function($category, $value) {
return ['category' => $category, 'value'=>$value];
}, $category, $values);
echo "<pre>";
var_dump(json_encode($array));
echo "</pre>";
Output:
string(74) "[{"category":"available","value":1},{"category":"notavailable","value":2}]"
I think you must doing like this:
$result = array();
for ($i = 0; $i < count($category); $i++) {
$result[] = array(
'category' => $category[$i],
'value' => $values[$i]
);
}
echo json_encode($result);
I have three arrays getting different post types, which are then merged for a drop down in the Wordpress admin. I'm trying to insert empty values/breaks to make the drop down easier to read.
Here are the arrays and the array_merge:
// creating an array of pages
$featpages = array();
$pages = get_pages();
$pages[""] = "";
foreach ($pages as $page) {
$featpages[ $page->post_title ] = $page->ID;
}
// creating an array of posts
$postargs = array('numberposts' => 0);
$featposts = array();
$posts = get_posts($postargs);
$posts[""] = "";
foreach ($posts as $post) {
$featposts[ $post->post_title ] = $post->ID;
}
// creating an array of activities
$actargs = array('post_type' => 'activity', 'numberposts' => 0);
$featacts = array();
$acts = get_posts($actargs);
$acts[""] = "";
foreach ($acts as $act) {
$featacts[ $act->post_title ] = $act->ID;
}
// creating a combined array of pages and tours
$links = array_merge((array)$featpages, (array)$featacts, (array)$featposts);
I was hoping the [""] = "";for each one would add an empty row between each set, but it only works for one - I guess because they look the same to the array_merge?
[""] = ""; will overwrite the next one
Use [] = ''; instead
I would like to know how to get the values into this array. Can someone please help?
Each box whether it is the in or outbox should only be listed once and then have multiple ids associated with them. I need to be able to tell which id came from what box. The ids that are in the array are only samples.
$arr =
array(
'Inbox'=> array('id' => array(8, 9, 15)),
'Outbox'=> array('id' => array(8, 9, 15))
);
Thanks
$inbox = $db->Query("SELECT * FROM mail_inbox");
$outbox = $db->Query("SELECT * FROM mail_outbox");
foreach($inbox as $key => $array)
{
$output['Inbox']]['id'][] = $array['msg_seq'];
}
foreach($outbox as $key => $array)
{
$output['Outbox']]['id'][] = $array['msg_seq'];
}
print_r($output);
This will give me the db fields from the inbox but I have no idea how to get the outbox in there as well. I also get undefined index for ['Box']
Now that I know what you are saying, to input stuff, do something like this to input it into the array:
$ID = 9;
$box = "Inbox";
$arr[$box]['id'][] = $ID;
or
$IDs = array(9,5,13);
$box = "Inbox";
$array = array($box => $IDs);
or if you were getting it from a Database
$dbarray[0] = array('ID' => 9,
'Box' => 'Outbox');
foreach($dbarray as $key => $array)
{
$output[$array['Box']]['ids'][] = $array['ID'];
}
Multi deminsional arrays
The key or index is the first bracket
$array[key]="foo"
is the same as
$array = array('key' => 'foo');
if there is a second bracket, it of the array inside the value part of an array. IE
$array['key']['key2'] = "bar";
is the same as
$array = array('key' => array('key2' => 'bar'));
Basically, multideminsional arrays are just arrays inside of arrays.
foreach($arr as $box => $array)
{
echo $box;
// $box = The Box
foreach($array['ids'] as $ID)
{
echo $ID . ",";
// $ID = The ID
}
echo "<br>";
}
Sample:
Outbox 9,13,15,
Inbox 9,13,15,
This goes through each box, echos the box name, and each ID inside of the box, and echos the ID.
To access only one box
foreach($arr['Inbox'] as $ID)
{
echo $ID . ",";
}
Sample Output:
9,13,15,