I have a script that creates an array in the following format
$named_array["vehicles"][0]['vehicle'] = "i100-1 " ;
$named_array["vehicles"][1]['vehicle'] = "i100-2 " ;
$named_array["vehicles"][2]['vehicle'] = "i100-46 " ;
What I want to do later in the script is get the index value[0-1-2 etc] from $named_array
but I only have the value ( i100-1 etc) as a query option , This is so I can alter it later. What I want to achieve is something like , what is the index value of $named_array where value is i100-2
this is output to json at the end .
I hope this makes sense ! any help please ?
function complex_index_of($named_array, $val){
for($i=0, $n=count($named_array['vehicles']); $i<$n; $i++){
if ($named_array['vehicles'][$i]['vehicle'] == $val)
return $i;
}
return -1;
}
echo complex_index_of($named_array, 'i100-2 ');
// output: 1
Try something like this (maybe create a function, if you need to do it more than once)
$needle = 'i100-1';
$vIndex = -1;
foreach ($named_array["vehicles"] as $index => $data) {
if($data['vehicle'] == $needle) {
$vIndex = $index;
break;
}
}
Related
I wrote a function to add a comma to every 8 zero of my number
I need to store value in PHP variable or array, but it's saved as "1.0E+30"
here is my PHP code:
function SplitHex($number) {
$number_split = str_split($number,1);
$number_split_revers = array_reverse($number_split);
$i = 0;
foreach ($number_split_revers as $key => $value ) {
if ( $value == 0) {
$i++;
if ( $i == 8 ) {
$number_split_revers[$key] = str_replace(0,",0",$value);
$i=0;
}
}
}
$final = '';
$number_final = array_reverse($number_split_revers);
foreach ($number_final as $value ) {
$final .= $value;
}
//$final = strval(implode("",$number_final));
return $final;
and I call the function :
$test[2] = SplitHex(1000000000000000000000000000000);
var_dump ($test);
print_r ($test);
the output of echo print_r var_dump are all same :
1.0E+30
but it must be 1000000,00000000,00000000,00000000
I searched a lot but couldn't find the right solution for this problem
FYI,
if the number if too long, it can not fit into 32 integer format in php, so it store it in float.
So you can not see that integer value if it exceed PHP_INT_MAX size.
But this is an alternative for this,
$test[2] = number_format(SplitHex(1000000000000000000000000000000),0,null,'');
var_dump ($test);
print_r ($test);
Give it a try, it should work.
I am working on a small php script, currently i have an array like this
[0] yassine#m, [1] yassine#f, [2] Dolmi#m , [3] yassine#l
I want PHP to check if there is a duplicated element (yassine in this case) and return something like this.
[0] yassine , [1] Dolmi#m
array_unique won't work. And i really don't have any clue how to solve this. If looked for a solution on the internet but doesnt seem to find it. Anyone can help Please ?
I think this may work for you.
First sort array by value, then use combination of substr(), strpos() and array_push() to create new array according to your need
then remove duplicate value using array_unique()
<?php
$oldarray = array("suman#1","suman#2","suman#3","sujan#1","suresh#2","");
// first sort array by value so matching value comes together
asort($oldarray);
$newarray = array();
$count = count($oldarray);
for($i=0; $i < $count-1; $i++){
$a = $oldarray[$i];
$b = $oldarray[$i+1];
if($i == 0)
$c = "";
else
$c = $oldarray[$i-1];
if(substr($a,0,strpos($a,"#")) == substr($b,0,strpos($b,"#")) || substr($a,0,strpos($a,"#")) == substr($c,0,strpos($c,"#")) ){
array_push($newarray,substr($a,0,strpos($a,"#")));
}
else
array_push($newarray,$a);
}
print_r($oldarray);
// now remove duplicate value from new array
$newarray = array_unique($newarray);
print_r($newarray);
?>
Check following solution
http://ideone.com/fork/kJlLbs
<?php
function generateUniqueList ($arr){
$ret = array();
foreach ($arr as $value) {
$key = explode("#", $value)[0];
if (array_key_exists($key, $ret)) {
$ret[$key] = $key;
}
else {
$ret[$key] = $value;
}
}
return array_values($ret);
}
$arr = array("yassine#m","yassine#f","Dolmi#m", "yassine#l");
$list = generateUniqueList ($arr);
print_r($list);
I am trying to manually sort a PHP array without making use of ksort.
This is how my code looks at the moment:
function my_ksort(&$arg){
foreach($arg as $key1 => $value1){
foreach($arg as $key2 => $value2){
if($key1 > $key2){
$aux = $value2;
$arg[$key2] = $value1;
$arg[$key1] = $aux;
}
}
}
}
It doesn't sort, I can't figure out how to make it sort.
You could try this:
function my_ksort(&$arg)
{
$keys=array_keys($arg);
sort($keys);
foreach($keys as $key)
{
$val=$arg[$key];
unset($arg[$key]);
$arg[$key]=$val;
}
}
I'm sorting the keys separately and then deleting the elements one-by-one and appending them to the end, in ascending order.
I'm using another sorting function (sort()), but if you want to eliminate all available sorting functions from your emulation, sort() is much easier to emulate. In fact, #crypticous's algorithm does just that!
This function return array in ASC. Take in consideration that I'm using goto which is supported in (PHP 5 >= 5.3.0)
function ascending_array($array){
if (!is_array($array)){
$array = explode(",", $array);
}
$new = array();
$flag = true;
iter:
$array = array_values($array); // recount array values with new offsets
(isset($min["max"])) ? $min["value"] = $min["max"] : $min["value"] = $array[0];
$min["offset"] = 0;
for ($i=0;$i<count($array);$i++){
if ($array[$i] < $min["value"]){ // redefine min values each time if statement executed
$min["value"] = $array[$i];
$min["offset"] = $i;
}
if ($flag){ // execute only first time
if ($array[$i] > $min["value"]){ // define max value from array
$min["max"] = $array[$i];
}
$flag = false;
}
if ($i === (count($array)-1)){ // last array element
array_push($new,$min["value"]);
unset($array[$min["offset"]]);
}
}
if (count($array)!=0){
goto iter;
}
print_r($new);
}
$arr = array(50,25,98,45);
ascending_array($arr); // 25 45 50 98
PS. When I was studying php, I wrote this function and now remembered that I had it (that's why I really don't remember what I am doing in it, though fact is it's working properly and hopefully there are comments too), hope you'll enjoy :)
DEMO
I was checking some issue related to this post and i wanted to give my insight about it ! here's what i would have done to implement php's sort :
$array_res = array();
$array = array(50,25,98,45);
$i=0;
$temp = $array[0];
$key = array_search($temp, $array);
while ($i<count($array)-1){
$temp = $array[0];
for($n=0;$n<count($array) ;$n++)
{
if($array[$n]< $temp && $array[$n] != -1 )
{
$temp = $array[$n];
}
else{continue;}
}
//get the index for later deletion
$key = array_search($temp, $array);
array_push($array_res, $temp);
/// flag on those which were ordered
$array[$key] =-1;
$i++;
}
// lastly append the highest number
for($n=0;$n<count($array) ;$n++)
{
if ($array[$n] != -1)
array_push($array_res, $array[$n]);
}
// display the results
print_r($array_res);
This code will display : Array
(
[0] => 25
[1] => 45
[2] => 50
[3] => 98
)
Short and sweet
function custom_ksort($arg)
{
$keys = array_keys($arg);
sort($keys);
foreach($keys as $newV)
{
$newArr[$newV] = $arg[$newV];
}
return $newArr;
}
It looks like your issue is that you're changing "temporary" characters $key1 and $key2 but not the actual arrays. You have to change $arg, not just $key1 and $key2.
Try something like:
$arr = Array(3=>"a",7=>"b");
print_r( $arr );
foreach( $arr as $k=>$v ){
unset($arr[$k]);
$arr[$k+1] = $v;
}
print_r($arr);
I have the following code:
if ( (isset($_GET['slAction'])) && ($_GET['slAction'] == "manage_label") )
{
$formData = getFormData();
foreach ($formData as $key => $value)
echo "(Key: $key, Value: $value )<br /> ";
}
// All form fields are identified by '[id]_[name]', where 'id' is the
// identifier of the form type. Eg. label, store etc.
// The field identifier we want to return is just the name and not the id.
function getFormData()
{
$form_fields = array_keys($_POST);
for ($i = 0; $i < sizeof($form_fields); $i++)
{
$thisField = $form_fields[$i];
$thisValue = $_POST[$thisField];
//If field is an array, put all it's values into one string
if (is_array($thisValue))
{
for ($j = 0; $j < sizeof($thisValue); $j++)
{
$str .= "$thisValue[$j],";
}
// Remove the extra ',' at the end
$thisValue = substr($str, 0, -1);
//Assosiative array $variable[key] = value
$formData[end(explode("_", $thisField))] = $thisValue;
}
else
$formData[end(explode("_", $thisField))] = $thisValue;
}
return $formData;
}
The output from this code is:
(Key: id, Value: 7276 )
(Key: name, Value: 911 Main brand )
(Key: email, Value: )
(Key: www, Value: )
(Key: categories, Value: Menswear,Womenswear,Shoes )
(Key: targetgroup, Value: )
(Key: keywords, Value: )
(Key: description, Value: Testing )
(Key: saveForm, Value: Save )
Now this is my problem. The form field called 'label_categories' are checkboxes and is returned as an array. The output, as you see, is "Menswear,Womenswear,Shoes".
If I try 'echo $formData['name']', the output is "911 Main brand".
If I try 'echo $formData['categories']. the output is blank / empty.
How come I can output the string 'name' and not the string 'categories'? In the getFormData() function, I turn the array into a string....
Any help appreciated.
That code can be greatly simplified:
// 1. no need for isset() check in the case where you're testing a value
// 2. use single quotes for strings where possible
if ($_GET['slAction'] == 'manage_label') {
$formData = getFormData();
// 3. Good rule is to use braces even when not necessary
foreach ($formData as $key => $value) {
echo "(Key: $key, Value: $value )<br /> ";
}
}
function getFormData() {
// 4. prefer explicit initialization
$formData = array();
// 5. this foreach is much cleaner than a loop over keys
foreach ($_POST as $k => $v) {
// 6. this is a lot cleaner than end(explode(...))
$name = preg_replace('!.*_!', '', $k);
if (is_array($v)) {
// 7. this implode() replaces 5 lines of code
// and is MUCH clearer to read
$formData[$name] = implode(',', $v);
} else {
$formData[$name] = $v;
}
}
return $formData;
}
instead of posting code, ill explain.
you cannot echo $_post['catagories'] because it is not a string or number. It is an array.
you can echo $_post['catagories'][nth number'] or echo implode(', ' $_post['catagories'])
I have the following code:
if ($_POST['submit'] == "Next") {
foreach($_POST['info'] as $key => $value) {
echo $value;
}
}
How do I get the foreach function to start from the 2nd key in the array?
For reasonably small arrays, use array_slice to create a second one:
foreach(array_slice($_POST['info'],1) as $key=>$value)
{
echo $value;
}
foreach(array_slice($_POST['info'], 1) as $key=>$value) {
echo $value;
}
Alternatively if you don't want to copy the array you could just do:
$isFirst = true;
foreach($_POST['info'] as $key=>$value) {
if ($isFirst) {
$isFirst = false;
continue;
}
echo $value;
}
Couldn't you just unset the array...
So if I had an array where I didn't want the first instance,
I could just:
unset($array[0]);
and that would remove the instance from the array.
If you were working with a normal array, I'd say to use something like
foreach (array_slice($ome_array, 1) as $k => $v {...
but, since you're looking at a user request, you don't have any real guarantees on the order in which the arguments might be returned - some browser/proxy might change its behavior or you might simply decide to modify your form in the future. Either way, it's in your best interest to ignore the ordering of the array and treat POST values as an unordered hash map, leaving you with two options :
copy the array and unset the key you want to ignore
loop through the whole array and continue when seeing the key you wish to ignore
in loop:
if ($key == 0) //or whatever
continue;
Alternative way is to use array pointers:
reset($_POST['info']); //set pointer to zero
while ($value=next($_POST['info']) //ponter+1, return value
{
echo key($_POST['info']).":".$value."\n";
}
If you're willing to throw the first element away, you can use array_shift(). However, this is slow on a huge array. A faster operation would be
reset($a);
unset(key($a));
On a array filled with 1000 elements the difference is quite minimal.
Test:
<?php
function slice($a)
{
foreach(array_slice($a, 1) as $key)
{
}
return true;
}
function skip($a)
{
$first = false;
foreach($a as $key)
{
if($first)
{
$first = false;
continue;
}
}
return true;
}
$array = array_fill(0, 1000, 'test');
$t1 = time() + microtime(true);
for ($i = 0; $i < 1000; $i++)
{
slice($array);
}
var_dump((time() + microtime(true)) - $t1);
echo '<hr />';
$t2 = time() + microtime(true);
for ($i = 0; $i < 1000; $i++)
{
skip($array);
}
var_dump((time() + microtime(true)) - $t2);
?>
Output:
float(0.23605012893677)
float(0.24102783203125)
Working Code From My Website For Skipping The First Result and Then Continue.
<?php
$counter = 0;
foreach ($categoriest as $category) { if ($counter++ == 0) continue; ?>
It is working on opencart also in tpl file do like this in case you need.
foreach($_POST['info'] as $key=>$value) {
if ($key == 0) { //or what ever the first key you're using is
continue;
} else {
echo $value;
}
}
if you structure your form differently
<input type='text' name='quiz[first]' value=""/>
<input type='text' name='quiz[second]' value=""/>
...then in your PHP
if( isset($_POST['quiz']) AND
is_array($_POST['quiz'])) {
//...and we'll skip $_POST['quiz']['first']
foreach($_POST['quiz'] as $key => $val){
if($key == "first") continue;
print $val;
}
}
...you can now just loop over that particular structure and access rest normally
How about something like this? Read off the first key and value using key() and current(), then array_shift() to dequeue the front element from the array (EDIT: Don't use array_shift(), it renumbers any numerical indices in the array, which you don't always want!).
<?php
$arr = array(
'one' => "ONE!!",
'two' => "TWO!!",
'three' => "TREE",
4 => "Fourth element",
99 => "We skipped a few here.."
) ;
$firstKey = key( $arr ) ;
$firstVal = current( $arr ) ;
echo( "OK, first values are $firstKey, $firstVal" ) ;
####array_shift( $arr ) ; #'dequeue' front element # BAD! renumbers!
unset( $arr[ $firstKey ] ) ; # BETTER!
echo( "Now for the rest of them" ) ;
foreach( $arr as $key=>$val )
{
echo( "$key => $val" ) ;
}
?>