This question already has an answer here:
How right replace value element in array?
(1 answer)
Closed 5 years ago.
I am using WordPress and have a custom post type setup with a set number of options, with the basic breakdown being something like this:
30" Round Table
Buffet
Cocktail
Dessert
Banquet Table
Buffet
Gift
DJ Table
I am trying to collect all items into a grouped collection, for use with <optgroup /> to show all tables under Buffet, all under Cocktail, etc. like so:
Buffet
30" Round Table
Banquet Table
Cocktail
Banquet Table
[and so on]
The PHP issue I'm running into is I have a master array that has all the types (buffet, cocktail, etc.) along with an (initially) empty array element called tables for me to add all the tables that support that specific type. Retrieving the options from ACF works fine, as does retrieving the individual posts from WordPress, so this is strictly a packaging issue to kick back as JSON. Here is a code example:
//gets the field associated with the different table types (Buffet, Cocktail, etc.)
$field = get_field_object('field_577ff065e6699');
$list = array();
//create the base array
foreach ($field["choices"] as $type) {
$list[] = array
(
"type" => $type, //Buffet, Cocktail, etc.
"tables" => array() //placeholder to add WP items
);
}
//now get all tables
$tablesQuery = new WP_Query( array( 'post_type' => 'table', 'posts_per_page' => -1, 'order' => 'ASC' ) );
//loop through and add the table(s) to their categories
while ( $tablesQuery->have_posts() ) : $tablesQuery->the_post();
//gets the types supported by this table
$tableTypes = get_field('options');
//individual types
foreach ($tableTypes as $tableType) {
//all types
foreach ($list as $supportedType) {
//see if there is a match and add it
if ($tableType == $supportedType["type"]) {
//add to the array since it matches
$table = array
(
"name" => get_the_title(),
"sqft" => (int)get_field('square_footage'),
"seats" => (int)get_field('seats')
);
array_push($supportedType["tables"], $table);
//shows the single table above, but nothing prior
print_r($supportedType);
}
}
}
endwhile;
wp_reset_postdata();
//all "tables" arrays are empty here
var_dump($list);
The output of print_r($supportedType) above ends up showing all data, however the tables entry is always only one element when it should be multiple:
Array
(
[type] => Buffet
[tables] => Array
(
[0] => Array
(
[name] => 30” Round Bistro/Cocktail Table
[sqft] => 42
[seats] => 2
)
)
)
Array
(
[type] => Cake
[tables] => Array
(
[0] => Array
(
[name] => 30” Round Bistro/Cocktail Table
[sqft] => 42
[seats] => 2
)
)
)
[.. snip ..]
Finally, when I do the var_dump($list) at the end, all of the types show up but their associated tables arrays are all empty:
array(11) {
[0]=>
array(2) {
["type"]=>
string(6) "Buffet"
["tables"]=>
array(0) {
}
}
[1]=>
array(2) {
["type"]=>
string(4) "Cake"
["tables"]=>
array(0) {
}
}
This has me completely lost, even though it has to be something incredibly basic that I'm missing. Any ideas why tables is empty, despite using array_push on the looped item? I also tried $supportedType["tables"][] = $table, but that has the same effect.
I think you're working with a copy of the array inside this foreach: foreach ($list as $supportedType) {
Try changing it to
foreach ($list as $key => $supportedType) {
...
// this operates on the copy
// array_push($supportedType["tables"], $table);
// operate on the original instead
array_push($list[$key]["tables"], $table);
...
}
Related
I am trying to remove Product element using unset from the array but it's not working. also, need to insert this array using MySql. How can I achieve this?
unset( $ar2['Product'] );
print_r($ar2);
Result showing with Product
Array
(
[0] => Array
(
[Product] => Resume, CV, vCard & Portfolio HTML5 Template
[Price] => 10
[Img] => http://localhost/envy-theme-new/wp-content/uploads/2019/01/cv.jpg
)
[1] => Array
(
[Product] => Runhill – Multipurpose Construction WP Theme
[Price] => 39
)
)
Your code should be
foreach ($ar2 as $array) {
unset( $array['Product'] );
}
Since you need to unset the key product from each element of the first array.
And to insert it you can use insert query inside the same loop.
foreach ($ar2 as $array) {
unset( $array['Product'] );
$sql = "insert into table_name column1,column2 values ($array['Price'],$array['Img'];";
}
I'm Assuming that you know how to insert values into MySql.
Otherwise use the following tutorial.
https://www.w3schools.com/php/php_mysql_insert.asp
Edit
Use this code inside your loop to remove multiple keys.
$keys = array('key1', 'key2');///all the keys you need to remove
foreach($keys as $key) {
unset($arr[$key]);
}
#kane
The error in your code is that you are not accessing the correct array index.
Array
(
[0] => Array
(
[Product] => Resume, CV, vCard & Portfolio HTML5 Template
[Price] => 10
[Img] => http://localhost/envy-theme-new/wp-content/uploads/2019/01/cv.jpg
)
[1] => Array
(
[Product] => Runhill – Multipurpose Construction WP Theme
[Price] => 39
)
)
In your array Product index occurs after a numeric index i.e.
You can use the approach of Yasii or you can try array_map to iterate over the array of array and unset Product key.
<?php
$data=array(
array(
'Product' => 'Resume, CV, vCard & Portfolio HTML5 Template',
'Price' => 10,
'Img' => 'http://localhost/envy-theme-new/wp-content/uploads/2019/01/cv.jpg'
),
array(
'Product' => 'Runhill – Multipurpose Construction WP Theme',
'Price' => 39
)
);
$data = array_map(function($arr){
unset($arr['Product']);
return $arr;
}, $data);
echo '<pre>';
var_dump($data);
As for insert PHP array to Mysql database you need to create an insert statement from the array values and have to handle missing index values like 'Img' key value is missing your second sub-array array
Before working with arrays learn about the best way to use arrays in php here:
https://code.tutsplus.com/tutorials/working-with-php-arrays-in-the-right-way--cms-28606
Using mysql ext to insert data into the db is no longer supported in PHP7.
Please use PDO instead.
A similar query is answered here:
Insert array into MySQL database with PHP
PDO Tutorial:
https://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
I have multidimensional array $items and I need to search it and then create new array(s).
This array is generated at the end of check-up in e-shop I'm trying to build, so array can be of random length. I need to create to create new array for every new supplier_id so I can send data to each and every one of them apart.
I already have code for making order but now it just takes all data at once. So in this particular example I'm expecting 3 multidimensional arrays that I can run trough my create_order code.
I know there are many threads talking about multidimensional arrays but none that I can understand enough to apply it in my case. Thanks very much for help.
Here is what $items may look like
array (4)
id => 36
count => 1
product => Nette\Database\Table\ActiveRow #7c60
table private => Nette\Database\Table\Selection #739c
data private => array (3)
product_id => 36
price => 219.0
supplier_id => 3
dataRefreshed private => FALSE
names => array (1)
en => "Product 1" (9)
array (4)
id => 180
count => 1
product => Nette\Database\Table\ActiveRow #938b
table private => Nette\Database\Table\Selection #a5f0
data private => array (3)
product_id => 180
price => 375.0
supplier_id => 4
dataRefreshed private => FALSE
names => array (1)
en => "Product 2" (9)
array (4)
id => 309
count => 1
product => Nette\Database\Table\ActiveRow #4c67
table private => Nette\Database\Table\Selection #8f56
data private => array (3)
product_id => 309
price => 40.0
supplier_id => 5
dataRefreshed private => FALSE
names => array (1)
en => "Product 3" (9)
So after few hours of digging I was amazed how easily it can by done
// searching for all unique supplier_id
$uniqueID = array();
foreach ($items as $item) {
if (!in_array($item['product']['supplier_id'], $uniqueID)) {
array_push($uniqueID, $item['id'] = $item['product']['supplier_id']);
}
}
// visual check of all unique *supplier_id*
dump($uniqueID);
// creation of array where I'm going to insert all necessary data
foreach ($uniqueID as $array) {
$defined_array = [];
// visual check for debugging purposes
dump("start");
// creating multiarray for every unique *supplier_id* and inserting data
foreach ($items as $item) {
if($item['product']['supplier_id'] == $array) {
$defined_array[] = $item;
}
}
// final check of all arrays + debug check for end --
// at the end this block is replaced by *create_order* code
foreach ($defined_array as $array) {
dump($array);
}
dump("end");
}
At the end I hope it will help to someone at least.
Hi I have built an array and in the final process of finishing the script.
I have been building a web crawler which scans specific links on sites specified. The crawler stores all the links in one page and then inserts them into another array (news_stories) with the links specified in them.
Now the way the new array is structured is like this.
Array
(
[0] => Array
(
[title] => The Qlick
[description] => Qlick
[keywords] => Search Engine, Web, Sexy, Noah Smith
[link] => http://www.theqlick.com/qlickdates.php
)
)
And that is difficult for me to implode and insert into a mysql table. Now my code below uses functions to grab titles, descriptions etc for each link it finds and then inserts them into the new array if they match.
Is there anyway to get this to delete the Array() at the top of the array and just have the array which specifies the title, description etc.
I want the output to look like:
[0] => Array
(
[title] => The Qlick
[description] => Qlick
[keywords] => Search Engine, Web, Sexy, Noah Smith
[link] => http://www.theqlick.com/qlickdates.php
)
Any ideas?
$bbc_values = array('http://www.theqlick.com/festivalfreaks.php', 'http://www.theqlick.com/qlickdates.php');
$news_stories = array();
foreach ($links as $link) {
$item = array(
"title" => Titles($link),
"description" => getMetas($link),
"keywords" => getKeywords($link),
"link" => $link
);
if (empty($item["description"])) {
$item["description"] = getWord($link);
}
foreach($bbc_values as $bbc_value) {
// note the '===' . this is important
if(strpos($item['link'], $bbc_value) === 0) {
$news_stories[] = $item;
}
}
}
$data = '"' . implode('" , "', $news_stories) . '"';
$query =
//CNN algorithm
print_r($news_stories);
PHP foreach() is an iterator, intended to let your programming perform the same action on a collection of data. In the existing design, the *$news_stories* array can contain multiple individual "sub-arrays", with each such "sub-array" being the unit of data you want to insert into your data base.
When you get down to the part about creating queries, you can use something like this:
foreach ($news_stories as $story)
{
/* CREATE AND RUN QUERY USING DATA IN $story */
}
You can use *var_dump()* to look at the contents of a $story array. When you do that, it will probably make sense instantly. PHP foreach() does not care if you have one element or a hundred elements. If you have zero elements, it will not run the code inside the control structure.
For some reason I having a hard time trying to arrange my data in arrays. Now I have a database that holds the title of a page, the content, id and date modified.
I have a function that calls onto another function that does a query and gets all the tables in that database table. Currently im just returning the titles of the pages because it's easy to do, but i'd like to use the id as well as the title. So I thought about using multidimensional arrays. I've used arrays in my life in different languages like C++, c#, java and so on, but got some reason the way PHP does it strikes me as odd, I think there is something im not getting.
So here i am looping through my records and putting the title in an array:
while ($row = $result->fetch_object())
{
$pages[$count] = $row->title;
$count++;
}
return $pages;
Would it be something like this:
$pages = array()
{
["records"]=>
array()
{
[$count]=> $row->id
[$count]=> $row->title
}
}
Would this give me an output of something like this:
[0]=> 1, homePage
[1]=> 2, page2
[2]=> 3, anotherPage
Is this right? is there a better way of doing it?
Thanks for your help.
From what I gathered, you're trying to achieve this:
$pages = array();
while ($row = $result->fetch_object()) {
// Empty bracket syntax allows indices to be automatically incremented
$pages[] = array("id" => $row->id, "title" => $row->title);
}
Outputs
Array
(
[0] => Array
(
[id] => 1
[title] => homePage
)
[1] => Array
(
[id] => 2
[title] => page2
)
[2] => Array
(
[id] => 3
[title] => page3
)
)
To access your page titles/IDs singularly:
echo $pages[2]['id']; // 3
echo $pages[2]['title']; // page3
To loop through all of the elements in the array:
foreach ($pages AS $page) {
echo $page['id'];
echo $page['title'];
}
I do this for my queries. This allows you to not need to know what is coming back. It does restrict by not only choosing what you want but I do that with my query if needed.
$strQuery = "your query";
$objResult = mysql_query( $strQuery );
$arrResults = array( );
foreach ( $objResult->result_array( ) as $arrRecord )
{
$arrResults[] = $arrRecord;
}
Then anything that comes back through your query is stored in the $arrResults array
Array
(
[0] => Array
(
[id] => 1
[title] => title1
)
[1] => Array
(
[id] => 2
[title] => title2
)
)
When retrieving a hierarchical structure from MySQL (table with one ID column and one PARENT column signifying the hierarchical relationships), I map the result into an enumerated array as follows (for this example the numbers are arbitrary):
Array ( [3] => Array ( [7] => Array () ), [7] => Array ( [8] => Array () ) )
Notice 3 is the parent of 7, and 7 is the parent of 8 (this could go on and on; and any parent could have multiple children).
I wanted to shrink this array into a nested multidimensional array as follows:
Array ( [3] => Array ( [7] => Array ( [8] => Array () ) ) )
That is, each NEW id is automatically assigned an empty array. Regardless, any ID's children will be pushed into their parent's array.
Take a look at the following illustration for further clarification:
alt text http://img263.imageshack.us/img263/4986/array.gif
This will probably result in a complicated recursive operation, since I always have to check whether a parent with any certain ID already exists (and if so, push the value into its array).
Is there a built-in php function that can assist me with this? Do you have any idea as to how to go about constructing this? For what it's worth I'm using this to built a navigation bar in wordpress (which can contain categories, subcategories, posts... essentially anything).
The idea is that you keep an auxiliary array with all the nodes (parent and child) you find. The values of this arrays are references that back your result.
This builds the tree in linear time (array_key_exists does a hash table lookup, which is on average O(1)):
//table contains (id, parent)
$orig = array(
11 => 8,
7 => 3,
8 => 7,
99 => 8,
16 => 8,
);
$childrenTable = array();
$result = array();
foreach ($orig as $n => $p) {
//parent was not seen before, put on root
if (!array_key_exists($p, $childrenTable)) {
$childrenTable[$p] = array();
$result[$p] = &$childrenTable[$p];
}
//child was not seen before
if (!array_key_exists($n, $childrenTable)) {
$childrenTable[$n] = array();
}
//root node has a parent after all, relocate
if (array_key_exists($n, $result)) {
unset($result[$n]);
}
$childrenTable[$p][$n] = &$childrenTable[$n];
}
unset($childrenTable);
var_dump($result);
gives
array(1) {
[3]=>
array(1) {
[7]=>
array(1) {
[8]=>
array(3) {
[11]=>
array(0) {
}
[99]=>
array(0) {
}
[16]=>
array(0) {
}
}
}
}
}
EDIT: unset $childrenTable in the end to clear reference flags. In practice, you will probably want to do the operation inside a function anyway.
This question and it's answers should be helpful to you: turn database result into array.
Be sure to read the PDF presentation by #Bill Karwin, specifically the topics regarding the Closure table.