How can i access the ID value without having to use the index?
in my code i do this ( $array[0]['data']['ID'] ) to access the ID value, i have many users and having to access them individually by the integer index is time consuming.
I prefer not to use a foreach loop because i my code i make calls to a remote API and it will query the API for each user which kills performane.
If i can convert the current array to one without the index that would be great and just access the ID value through ( $array['data']['ID'] ).
[0] => Array ( [data] => Array ( [ID] => 370
[1] => Array ( [data] => Array ( [ID] => 405
I found that the code below lags my page load tremendously:
foreach ($search_users as $k => $user):
if (!empty($street[0])) {
$db = prettyAddress(get_user_meta($user->ID, 'company_address', true));
$match = matchAddress($formattedAddress, $db, count($street));
if ($match == false)
unset($search_users[$k]);
}
endforeach;
It is referenced in my question here:
Why does my foreach take forever to load
$location = !empty($_POST['saddress']) ? $_POST['saddress'] : "NA";
$display = false;
if ($location != "NA")
$display = true;
global $wpdb;
$location = $_POST['saddress'];
$street = explode(',', $location);
$cat = $_GET['specializingin'];
$args = array(
'meta_query' => array(
array(
'key' => 'scategory',
'value' => $_GET['specializingin'],
'compare' => 'LIKE'
),
array(
'key' => 'specialties',
'value' => ($_GET['specialitiesin'] == 'All Specialties' ? '' : $_GET['specialitiesin']),
'compare' => 'LIKE'
),
),
);
$search_users = get_users($args);
$formattedAddress = prettyAddress($location);
You can assign a variable to the current element of the array:
$current = $array[0];
Then you can access
$current['data']['ID'];
If you need to be able to modify the array using this, you should use a reference:
$current =& $array[0];
you can do this in a loop:
foreach ($array as $current) {
echo $current['data']['ID'];
}
Related
I have following foreach loop
$selectedids = "1255;1256;1257";
$selectedidsarr = explode(';', $selectedids);
$idstand = '1';
foreach ($selectedidsarr as $item) {
$output1 = $idstand++;
echo "<li>product_id_$output1 = $item,</li>";
}
I want to add the output of the above loop inside following associative array
$paramas = array(
'loginId' => $cred1,
'password' => $credpass1,
'orderId' => $orderid,
'offer' => $offerid,
'shipid' => $shipcharge
)
So that the final array will look like this;
$paramas = array(
'loginId' => $cred1,
'password' => $credpass1,
'orderId' => $orderid,
'offer' => $offerid,
'shipid' => $shipcharge,
'product1_id' => 1255,
'product2_id' => 1256,
'product3_id' => 1257,
)
I tried creating following solution but its not working for me
$selectedids = $boughtitem;
$selectedidsarr = explode(';', $selectedids);
$idstand = '1';
foreach ($selectedidsarr as $item) {
$idoutput1 = $idstand++;
$paramas [] = array (
'product$idoutput1_id' => $item,
);
}
Need advice.
You don't need to define a new array, just set the key of the current array to the value you want, in the form of $array[$key] = $value to get an array that looks like [$key=>$value], or in your case...
$paramas['product' . $idoutput1 . '_id'] = $item;
Here is what I currently have with my code:
$wp_query = new WP_Query([
'post_type' => 'office',
'post_status' => 'any',
'posts_per_page' => -1,
]);
$offices = [];
if (count($wp_query->posts) > 0) {
$offices = $wp_query->posts;
}
foreach ($offices as $office) {
/* Set the $office variable to return all office names */
$office = get_post_meta($office->ID, '_office_id');
}
I have my $offices = [] .. empty array that returns the following:
Array (
[0] => WP_Post Object
(
[ID] => 52856
then I have my $office variable in the foreach that returns the get_post_meta for _office_id that returns the following:
Array (
[0] => RIODEJANFHBRZ )
How could I build an array out of the $office varible and put the office value as assigned array key so it's [_office_id] => etc..? Tried all sorts of ways and was unable too.
Example:
Array (
[_office_id] => RIODEJANFHBRZ )
Add true in the last param of the function. Adding true will give you a single result and not an array.
foreach ($offices as $office) {
$key['_office_id'] = get_post_meta($office->ID, '_office_id', true);
print_r2($key);
}
Refer to the this URL:
https://developer.wordpress.org/reference/functions/get_post_meta/
Hope this helps.
I've got it somewhat figured out but I don't think it's 100% right just yet.
Here is my result:
Array (
[_office_id] => Array
(
[0] => RIODEJANFHBRZ
)
)
Here is the code:
foreach ($offices as $office) {
$key['_office_id'] = get_post_meta($office->ID, '_office_id');
print_r2($key);
}
Isn't it supposed to be:
[_office_id] => RIODEJANFHBRZ
This is my simple looper code
foreach( $cloud as $item ) {
if ($item['tagname'] == 'nicetag') {
echo $item['tagname'];
foreach( $cloud as $item ) {
echo $item['desc'].'-'.$item['date'];
}
} else
//...
}
I need to use if method in this looper to get tags with same names but diferent descriptions and dates. The problem is that I dont know every tag name becouse any user is allowed to create this tags.
Im not really php developer so I'm sory if it's to dummies question and thanks for any answers!
One possible solution is to declare a temporary variable that will hold tagname that is currently looped through:
$currentTagName = '';
foreach( $cloud as $item ) {
if ($item['tagname'] != $currentTagName) {
echo $item['tagname'];
$currentTagName = $item['tagname'];
}
echo $item['desc'] . '-' . $item['date'];
}
I presume that your array structure is as follows:
$cloud array(
array('tagname' => 'tag', 'desc' => 'the_desc', 'date' => 'the_date'),
array('tagname' => 'tag', 'desc' => 'the_desc_2', 'date' => 'the_date_2'),
...
);
BUT
This solution raises a problem - if your array is not sorted by a tagname, you might get duplicate tagnames.
So the better solution would be to redefine your array structure like this:
$cloud array(
'tagname' => array (
array('desc' => 'the_desc', 'date' => 'the_date'),
array('desc' => 'the_desc_2', 'date' => 'the_date_2')
),
'another_tagname' => array (
array('desc' => 'the_desc_3', 'date' => 'the_date_3'),
...
)
);
and then you can get the data like this:
foreach ($cloud as $tagname => $items) {
echo $tagname;
foreach($items as $item) {
echo $item['desc'] . '-' . $item['date'];
}
}
Is there a better way of doing this PHP code? What I'm doing is looping through the array and replacing the "title" field if it's blank.
if($result)
{
$count = 0;
foreach($result as $result_row)
{
if( !$result_row["title"] )
{
$result[$count]["title"] = "untitled";
}
$count++;
}
}
Where $result is an array with data like this:
Array
(
[0] => Array
(
[title] => sdsdsdsd
[body] => ssdsd
)
[1] => Array
(
[title] => sdssdsfds
[body] => sdsdsd
)
)
I'm not an experienced PHP developer, but I guess that the way I've proposed above isn't the most efficient?
Thanks
if($result) {
foreach($result as $index=>$result_row) {
if( !$result_row["title"] ) {
$result[$index]["title"] = "untitled";
}
}
}
You don't need to count it. It's efficient.
if ($result)
{
foreach($result as &$result_row)
{
if(!$result_row['title'])
{
$result_row['title'] = 'untitled';
}
}
}
Also, you may want to use something other than a boolean cast to check the existence of a title in case some young punk director releases a movie called 0.
You could do something like if (trim($result_row['title']) == '')
Mixing in a little more to #Luke's answer...
if($result) {
foreach($result as &$result_row) { // <--- Add & here
if($result_row['title'] == '') {
$result_row['title'] = 'untitled';
}
}
}
The key is the & before $result_row in the foreach statement. This make it a foreach by reference. Without that, the value of $result_row is a copy, not the original. Your loop will finish and do all the processing but it won't be kept.
The only way to get more efficient is to look at where the data comes from. If you're retrieving it from a database, could you potentially save each record with an "untitled" value as the default so you don't need to go back and put in the value later?
Another alternative could be json_encode + str_replace() and then json_decode():
$data = array
(
0 => array
(
'title' => '',
'body' => 'empty',
),
1 => array
(
'title' => 'set',
'body' => 'not-empty',
),
);
$data = json_encode($data); // [{"title":"","body":"empty"},{"title":"set","body":"not-empty"}]
$data = json_decode(str_replace('"title":""', '"title":"untitled"', $data), true);
As a one-liner:
$data = json_decode(str_replace('"title":""', '"title":"untitled"', json_encode($data)), true);
Output:
Array
(
[0] => Array
(
[title] => untitled
[body] => empty
)
[1] => Array
(
[title] => set
[body] => not-empty
)
)
I'm not sure if this is more efficient (I doubt it, but you can benchmark it), but at least it's a different way of doing the same and should work fine - you have to care about multi-dimensional arrays if you use the title index elsewhere thought.
Perhaps array_walk_recursive:
<?php
$myArr = array (array("title" => "sdsdsdsd", "body" => "ssdsd"),
array("title" => "", "body" => "sdsdsd") );
array_walk_recursive($myArr, "convertTitle");
var_dump($myArr);
function convertTitle(&$item, $key) {
if ($key=='title' && empty($item)) {$item = "untitled";}
}
?>
If you want sweet and short, try this one
$result = array(
array(
'title' => 'foo',
'body' => 'bar'
),
array(
'body' => 'baz'
),
array(
'body' => 'qux'
),
);
foreach($result as &$entry) if (empty($entry['title'])) {
$entry['title'] = 'no val';
}
var_dump($records);
the empty() will do the job, see the doc http://www.php.net/manual/en/function.empty.php
Array
(
[00000000017] => Array
(
[00000000018] => Array
(
[00000000035] => I-0SAYHADW4JJA
[00000000038] => I-RF10EHE25KY0
[00000000039] => I-8MG3B1GT406F
)
[00000000019] => I-7GM4G5N3SDJL
)
[00000000025] => Array
(
[00000000011] => I-HT34P06WNMGJ
[00000000029] => I-U5KKT1H8J39W
)
[00000000040] => I-GX43V2WP9KPD
[00000000048] => I-XM526USFJAH9
[00000000052] => I-M414RK3H987U
[00000000055] => I-GABD4G13WHX7
)
I have the above array and i want to create a treeview display..
any recommendation ?
I guess i have to elaborate furthe on my question..
I want to store those array according to the level of array..
Example , I want something look like this :
[level_1]=> 00000000017,00000000025,00000000040, 00000000048, 00000000052
[level_2]=> 00000000018,00000000019, 00000000011, 00000000029
[level_3]=> 00000000035, 00000000038, 00000000039
You want a modified breadth-first search. This has the correct results for your sample structure:
<?php
function BFTraverse(&$tree = NULL, $depth = 0)
{
if (empty($tree))
return FALSE;
$keys = array_keys($tree);
$struct["lvl_$depth"] = $keys;
foreach ($keys as $key)
{
if (is_array($tree[$key]))
{
$struct = array_merge_recursive($struct, BFTraverse($tree[$key], $depth + 1));
}
}
return $struct;
}
$data = array
('00000000017' => array
(
'00000000018' => array
(
'00000000035' => 'I-0SAYHADW4JJA',
'00000000038' => 'I-RF10EHE25KY0',
'00000000039' => 'I-8MG3B1GT406F'
),
'00000000019' => 'I-7GM4G5N3SDJL'
),
'00000000025' => array
(
'00000000011' => 'I-HT34P06WNMGJ',
'00000000029' => 'I-U5KKT1H8J39W'
),
'00000000040' => 'I-GX43V2WP9KPD',
'00000000048' => 'I-XM526USFJAH9',
'00000000052' => 'I-M414RK3H987U',
'00000000055' => 'I-GABD4G13WHX7'
);
$var = BFTraverse($data);
$i = 0;
foreach ($var as $level)
echo "Level " . ++$i . ': ' . implode(', ', $level) . "\n";
?>
The output is:
Level 1: 00000000017, 00000000025, 00000000040, 00000000048, 00000000052, 00000000055
Level 2: 00000000018, 00000000019, 00000000011, 00000000029
Level 3: 00000000035, 00000000038, 00000000039
edit: Modified in the sense that you want the keys and not the node values.
I ran into the same problem recently and this article by Kevin van Zonneveld helped me out.
Basically you have to use a recursive function. Check out the article, it's what you need!