Array item call - php

I have problem with calling Array which are form redux framework to wordpress
when i execute this:
print_r ($ka_opt['theme-order']);
i have this result:
Array ( [nr2] => 1 [nr3] => 1 [nr1] => 1 )
I need to call specific item from this array for example first item, i tryed this to call first possition but dont work:
echo $ka_opt['theme-order'][0];
whats wrong? i dont know how to call variable

That is an associative array, not a numerically keyed array. You can't use numerical keys with associative arrays. You must use their proper keys:
echo $ka_opt['theme-order']['nr2'];
If you want the first item you can us array_shift():
echo array_shift($ka_opt['theme-order']);
If you want a deeper array element you can use array_slice():
// get second element, assuming PHP5.4+
echo array_slice(array_values($ka_opt['theme-order']), 1, 1)[0];
And, of course, you can always loop through it to get the values you seek.

Related

Restructure 2d array so that column values become row values (transpose but preserve first level keys)

The situation is as follows. I have a parent array which looks like the following:
$parent = [
1 => ['test1', 'test2'],
2 => ['test1_1', 'test2_2'],
];
I would like to group the data by column.
Desired result:
[
1 => ['test1', 'test1_1'],
2 => ['test2', 'test2_2'],
]
1 parent array called parent contains 2 arrays inside. I want to combine these two so that they have the same values as stated above. So this would mean that the arrays should be combined based on index number.
Since I do not make use of string keys, how would I accomplish this? I believe that there is no build in function available for this situation.
I would imagine that I could start beginning to create a new array and use a for loop through the parent array.
I tried the array-combine function however, this is NOT displaying the results I want.
[
1 => ['test1' => 'test1_1', 'test2' => 'test2_2'
]
If you need to preserve those first level keys, you can re-apply them after tranposing.
Code: (Demo)
var_export(
array_combine(array_keys($parent), array_map(null, ...$parent))
);
Otherwise, you can just transpose and accept the re-indexed first level keys. Honestly, I can't see any good reason to preserve the first level keys because by transposing, you remove the initial association between first level keys and the row values.
Code: (Demo)
var_export(
array_map(null, ...$parent)
);
If these techniques do not suit your actual project data, then we will need a more realistic sample array to be provided in your question body.
Loop over the keys of the top-level array. Then use the current index of the iteration to get the corresponding columns of the nested arrays.
$result = [];
foreach (array_keys($parent) as $i => $k) {
$result[$k] = array_column($parent, $i);
}
DEMO
This assumes the number of rows is the same as the number of columns. It's not clear what you expect the result to be if that's not true.

how can i print a specific portion of array in php?

I am trying to print a number from an array. But when i do this:
echo $results[0][0];
i get error.I tried to print the whole array using print_r() function
echo print_r($results);
Then i get this result:
Array ( [0] => stdClass Object ( [lastOrderProcessedNumber] => 109089875875875 ) ) 1
I just need to print "109089875875875" this number
How can i do that?
Thank you in advance
print_r() is a great way to inspect the contents of a variable. What it is showing you is that your variable holds an array whose first element (at index 0) is an object with an lastOrderProcessedNumber attribute. In PHP, you use -> to access object properties, so you should be able to retrieve the 109089875875875 value like this:
$results[0]->lastOrderProcessedNumber
As you can see from the print_r result, the indexed result is an object:
// $results is an 'Array' (access with square brackets)
Array
(
// Index 0 is an Object (access with arrow operator)
[0] => stdClass Object
(
[lastOrderProcessedNumber] => 109089875875875
)
)
This means you have to access the property through the arrow operator, like so:
$results[0]->lastOrderProcessedNumber
If you're expecting to only have one result, or to grab the first result from $results, you can make use of reset:
reset($results)->lastOrderProcessedNumber
If you see $results is an array of objects, that means that $results[0] is an object, not an array, so you can't access its attributes as an array but instead as an object. Like this:
$results[0]->lastOrderProcessedNumber;

Delete one item from array with matching keys

I have an array
$array = ['f'=>'foo', 'f'=>'foo', 'f'=>'foo','g'=>'good'];
and I want to delete only one item from this array with matching key, like the following:
unset($array['f']);
However, this will delete the all items with this matching key 'f' and only one item will remain. Is there a way to do something like this, but apply it only to the first matching item in the array?
First of all you have a syntax error.
$array=$array(['f'=>'foo', 'f'=>'foo', 'f'=>'foo','g'=>'good']);
You have an $ extra and [] extras, and you can't have a lots off records with the same key(because the last one will override the previously)... The correct way to define
$array= array('f'=> array('foo', 'foo2', 'foo3'), 'g'=>'good');
The values will be a new array inside de F key. And then you can remove only one record
unset($array['f'][0]);
now your arrays var_dump:
$array= array('f'=> array('foo2', 'foo3'), 'g'=>'good');
i have solved this by using this as per cmorrissy comment there will be only one item so that variable was showing me qty, i have to check if
if($product[$id]['quantity']>1){ $product[$id]['quantity']--;}else{unset($product[$id]);}
if you var_dump($array); this would be the output
var_dump($array);
array(
f => foo
g => good
)
since you have an array with the same index it will be displayed as one, and thats why it will be deleted

Fast method for Looping through Array to match a common ID in a second array

I'm trying to systematically loop through 2 arrays, and match their values for some quick processing. Let me set up my specific situation:
Array 1
productID,
companyID,
name,
price
Array 2
companyID,
name,
rebate1,
rebate2
I want to loop through Array 1, and when the companyID matches an ID inside of Array 2, I will do some quick math based on the rebate1, rebate2 values for that companyID.
Right now I am looping through Array 1, and then on EACH item in Array 1 I loop through the entire Array 2 to see if the companyID exists. I know this can't be the fastest/cleanest solution...
EDIT
The key values for Array 1 look like:
$array1[0]['productID']
$array1[0]['companyID'] (etc...)
$array1[1]['productID']
$array1[1]['companyID'] (etc...)
The key values for Array 2 look like:
$array2[0]['companyID']
$array2[0]['rebate1'] (etc...)
$array2[1]['companyID']
$array2[1]['rebate1'] (etc...)
Use the companyId as key for Array 2, i.e., make sure that
$Array2[$Array1[$i]['companyID']]['companyID'] == $Array1[$i]['companyID']
This gives you constant time lookup of companies in Array 2 based on companyID and you can do your calculation with
$Array2[$Array1[$i]['companyID']]['rebate1']`
and
$Array2[$Array1[$i]['companyID']]['rebate2']`
Example:
foreach ($Array1 as $value) {
if (isset($Array2[$value['companyID']])) {
//TODO: use $Array2[$value['companyID']] for calculation
} else {
// TODO: handle case companyID not in $Array2
}
}
What approximate sizes do you expect for each of your arrays?
While as you say, your method isn't certainly the fastest (looks like 0(n²)), below 10'000 elements in each array I doubt you can see any significant speed difference.
If you have 150'000 in array1 and 200'000 in array2, that's a whole other story and you'll have to look for an algorithm that is rather 0(log n).
Edit:
As mentioned above, let's just make your array associative if you can:
Instead of:
Array2 = array(
0 => array(
'Company_id' => 'Hello',
'rebate_1' => '50%',
)
);
Make it:
Array2 = array(
'Hello' => array(
'rebate_1' => '50%',
)
);
And then use:
if (isset(array2[$company_id]))
{
// do your stuff
}
If you can't modify Array2's structure where it's coming from, you should transform it on the fly in your search function's scope, so that it looks like above, and then use the transformed array. Transforming Array2 into an associative one shouldn't take too long, for the number of elements you say you have.
The easiest way I can think of is to use the companyID as the key for Array 2:
$companies[$companyID]=array($name,$rebate1,$rebate2)
and then you just reference it directly looping Array 1
$products[$x]=array($productID,$companyID,$name,$price);
...
$newprice1=$products[$x][3]/$companies[$products[$x][1]][1];
$newprice2=$products[$x][3]/$companies[$products[$x][1]][2];
My answer is slightly different from the first one, mind the arrays...
You can create a new array indexed by the company id as follows:
$cid = array_map(function($a) {return $a['companyID'];}, $array2);
$new2 = array_combine($cid, $array2);
With that, you can loop through the first array and access the data:
foreach ($array1 as $key => $value){
$rebate1 = $new2[$value['companyID']]['rebate1'];
$rebate2 = $new2[$value['companyID']]['rebate2'];
}

how to put an array item to the end in php?

how to put an array item to the end in php?
I want to put some item of array to the last position , when I loop and output the $arr to html, this will keep the 'other' item always at the end. what is the best and easy way to do it?
<?php
$arr=array(
'a'=>'hello',
'game'=>'boy',
'other'=>'good',
'name'=>'jimmy',
//...
);
// how to resort $arr to put other item to then end of $arr
$arr=array(
'a'=>'hello',
'game'=>'boy',
'name'=>'jimmy',
//...
'other'=>'good'
);
?>
with the example you have given ksort($arr) would sort it alphabetically and put the other item to the end.
second option is to remove the other item from the array using array_slice and then placed it in the back using array_merge
Assuming you're not simply asking to sort the array based on the alphabetical property of the keys, given your array:
$arr=array(
'a'=>'hello',
'game'=>'boy',
'other'=>'good',
'name'=>'jimmy',
);
You have to take the old key out first, while saving its value:
$old = $arr['other'];
unset($arr['other']);
Then, append it to the array like this:
$arr += array('other' => $old);
First store all the element that you required.
Like
$arr=array(
'a'=>'hello',
'game'=>'boy',
'name'=>'jimmy');
After that add
$arr['other']='good';
Now other element is always at last.....

Categories