September 17, 2013

Convert String in Array JQUERY

User2789569’s Question:

I have the data array return of the server :

data.arr = [[Date.UTC(2013, 9, 17),1],[Date.UTC(2013, 9, 18),5],[Date.UTC(2013, 9, 19),2],[Date.UTC(2013, 9, 20),4]]

    [0] "[Date.UTC(2013, 9, 17),1]" String
    [1] "[Date.UTC(2013, 9, 18),5]" String
    [2] "[Date.UTC(2013, 9, 19),2]" String
    [3] "[Date.UTC(2013, 9, 20),4]" String

I need to pass only value to a function that recepeit an array[i,y], i need that stay following; i need to remove the “”.

    [0] [Date.UTC(2013, 9, 17),1]
    [1] [Date.UTC(2013, 9, 18),5]
    [2] [Date.UTC(2013, 9, 19),2]
    [3] [Date.UTC(2013, 9, 20),4]

How to do it?

data.arr = [[Date.UTC(2013, 9, 17),1],[Date.UTC(2013, 9, 18),5],
[Date.UTC(2013, 9, 19),2],[Date.UTC(2013, 9, 20),4]]

This code should already give you a timestamp value, but I am assuming you are asking about when it is treated as string so as suggested in comments, you can use eval to evaluate the string as Data Object.

for(var i = 0; i < data.arr.length; i++) {
     data.arr[i] = [data.arr[i][0], eval(data.arr[i][1])];
}

Here is a demo: http://jsfiddle.net/8eLEH/

September 12, 2013

PHP Array during echo

Anthonytherockjohnson’s Question:

I have an assignment to do but am having trouble understanding the given psuedocode :/

<?php
$bucket = new array();
print $bucket->addrocks('Rock1')->addrocks('rock2')-
>addrocks('Rock3');

echo "<h1>My Bucket</h1>";
echo "<ul>";
foreach($bucket as $rock){
echo "<li>". $rock ."</li>";
}
echo "</ul>";
?>

Now my trouble starts with understanding how they want me to construct the array after the “print” call? i am not looking for a direct answer to this just maybe a tutorial link or a finger in the right direction

Thank you in advance

Well unlikely but may be the array is not an construct but an class in your pseudocode. My assumptions depend on the use of new keyword and the user of -> and addrocks which looks like a method.

So, create a class called array (stupid I know) and get going.

However the user of foreach($bucket) also shows that it expects $bucket to be array. So decide wisely 🙂

May be use a magic method called __toString() inside the class and return back the array.

September 10, 2013

Check whether array has keys that don't match a list

Donny P’s Question:

What is the easiest way to check if an has array keys that don’t match a particular list?

$a = array(
  [ignore_me] => "blah blah blah",
  [name] => "Don"
);

does_array_have_non_ignored_entries($a); // returns true

I can think of a ton of ways to write this function, didn’t know if PHP has a quick solution. Best one I have is this:

$length = count($a);
$ignored_entry = (in_array($a, 'ignore_me') ? 1 : 0;
if ($length - $ignored_entry > 0) {...}

How about this?

$count = isset($a['ignore_me']) ? count($a) -1 : count($a);

Substract 1, if that key is found, else use the full length.

September 2, 2013

how to delete an array which contains a specified string

Zaz’s Question:

I have an array called “VALUES” that contains multiple arrays. In these array there is a field named “test”, I only want the arrays pointed out that contains the number 4 in the test field.

my current output for Values array:

Array ( 

[0] => Array ( [entry_id] => 41149 [o_number] => 000001 [test1] => 000001 [test2] => 1234 [lev] => Ja [fak] => Mail [beta] => 30 [test] => 4 ) 

[1] => Array ( [entry_id] => 41142 [o_number] => 000202[test1] => 000202 [test2] => 1234 [lev] => Ja [fak] => Mail [beta] => 30 [test] => 4 ) 

[2] => Array ( [entry_id] => 41103 [o_number] => 000003 [test1] => 000003 [test2] => 1234 [lev] => Ja [fak] => Mail [beta] => 30 [test] => 4 ) 

[3] => Array ( [entry_id] => 41101 [o_number] => 000044 [test1] => 000044 [test2] => 1234 [lev] => Ja [fak] => Manuel/brev [beta] => 10 [test] => 2 ) 

[4] => Array ( [entry_id] => 41100 [o_number] => 000542 [test1] => 000542 [test2] => 1234 [lev] => Ja [fak] => Mail [beta] => 30 [test] => 4 ) 

[5] => Array ( [entry_id] => 41088 [o_number] => 001231 [test1] => 001231 [test2] => 1234 [lev] => Ja [fak] => Mail [beta] => 30 [test] => 3 ))

desired output:

Array ( 

[0] => Array ( [entry_id] => 41149 [o_number] => 000001 [test1] => 000001 [test2] => 1234 [lev] => Ja [fak] => Mail [beta] => 30 [test] => 4 ) 

[1] => Array ( [entry_id] => 41142 [o_number] => 000202[test1] => 000202 [test2] => 1234 [lev] => Ja [fak] => Mail [beta] => 30 [test] => 4 ) 

[2] => Array ( [entry_id] => 41103 [o_number] => 000003 [test1] => 000003 [test2] => 1234 [lev] => Ja [fak] => Mail [beta] => 30 [test] => 4 ) 

[3] => Array ( [entry_id] => 41100 [o_number] => 000542 [test1] => 000542 [test2] => 1234 [lev] => Ja [fak] => Mail [beta] => 30 [test] => 4 ))

I tried with a foreach but it didn’t work

    foreach ($values as $key) 
    {
        if($key === 4)
        {
//This will only show
    print_r($key);

//delete array?

        }
    }

Try following codes:

foreach ($values as $key => &$value) 
{
   if($value['test'] != "4")
      unset($values[$key]);
}

var_dump($values);

Since you are using multidimensional arrays it is not that easy to check whether or not any array consists of that key, without traversing through it. In order to traverse, you can use foreach

foreach($values as $array) {
    //Now here you can check if the there is `test` index available or is of value `4`

    if(isset($array['test'])) && $array['test'] == '4') {
        //Only then output it
        var_dump($array);
    }
}

It is that simple.

July 4, 2013

How to merge array and preserve keys?

Joe’s Question:

I have two arrays:

$array1 = array('a' => 1, 'b' => 2, 'c' => 3);
$array2 = array('d' => 4, 'e' => 5, 'f' => 6, 'a' => 'new value', '123' => 456);

I want to merge them and keep the keys and the order and not re-index!!

How to get like this?

Array
(
    [a] => new value
    [b] => 2
    [c] => 3
    [d] => 4
    [e] => 5
    [f] => 6
    [123] => 456
)

I try to array_merge() but it will not be preserved the keys:

print_r(array_merge($array1, $array2));

Array
(
    [a] => 'new value'
    [b] => 2
    [c] => 3
    [d] => 4
    [e] => 5
    [f] => 6
    [0] => 456
)

I try to the union operator but it will not overwriting that element:

print_r($array1 + $array2);

Array
(
    [a] => 1   <-- not overwriting
    [b] => 2
    [c] => 3
    [d] => 4
    [e] => 5
    [f] => 6
    [123] => 456
)

I try to swapped place but the order is wrong, not my need:

print_r($array2 + $array1);

Array
(
    [d] => 4
    [e] => 5
    [f] => 6
    [a] => new value 
    [123] => 456
    [b] => 2
    [c] => 3
)

I dont want to use a loop, is there a way for high performance?

You’re looking for array_replace():

$array1 = array('a' => 1, 'b' => 2, 'c' => 3);
$array2 = array('d' => 4, 'e' => 5, 'f' => 6, 'a' => 'new value', '123' => 456);
print_r(array_replace($array1, $array2));

Available since PHP 5.3.

Update

You can also use the union array operator; it works for older versions and might actually be faster too:

print_r($array2 + $array1);

array_replace_recursive() or array_replace() is the function you are looking for

$array1 = array('a' => 1, 'b' => 2, 'c' => 3);
$array2 = array('d' => 4, 'e' => 5, 'f' => 6, 'a' => 'new value', '123' => 456);


var_dump(array_replace_recursive($array1, $array2));

Demo

June 29, 2013

Unsort in array

Alex’s Question:

Good day.

I would be like get 3 keys from $arr where value $arN[0] will be more than other…

Code:

$ar1=array(201,281);
$ar2=array(1252760,1359724);
$ar3=array(452760,34349724);
$ar4=array(1260,134344);
$ar5=array(232750,1359724);
$ar6=array(60,1439724);

$arr[]=array(6299927 => $ar1);
$arr[]=array(1252760 => $ar2);
$arr[]=array(3432444 => $ar3);
$arr[]=array(3435543 => $ar4);
$arr[]=array(7645466 => $ar5);
$arr[]=array(4574534 => $ar6);

Next function sorting array $a descending:

function cmp($a, $b)
{
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? 1 : -1;
}

$a = array(3, 2, 5, 6, 1);

usort($, "cmp");

foreach ($a as $key => $value) {
    echo "$key: $valuen";
}
outpoot: 0:6 1:5 2:4 3:2 4:1

But how change this function for my example(for my big array)?

Tell me please how make this?

How write right?

Very confusing but I think you are looking for something like this. It will give you the index of the array whose first item is greater than the first item in the next array.

foreach($arr as $key => $array) {
    if($array[0] > $arr[$key+1][0]) {
       echo $key;
    }
}
May 30, 2013

PDO – get two select values into an array

NojoRu’s Question:

I have this PDO:

$id = 1;
$title = 'resourceName';
$url = 'resourceURL';
$result = array($title => $url);

include('../dbconnect.php');

$pdo = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_password);
$stmt = $pdo->prepare("SELECT resourceName, resourceURL FROM Resources WHERE categoryID = :id");
$stmt->bindParam(':id', $id);
$stmt->execute(array_values($result));
$row = $stmt->fetchAll();
print_r($row);

I am just getting this error:
Warning: PDOStatement::execute() [pdostatement.execute]: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

How can make the PDO result be an array where resourceName is the key and resourceURL is the value?

You are binding unneeded parameters to the query.

$stmt->bindParam(':id', $id);
$stmt->execute(array_values($result)); //On this line. These parameters are 
                                         not needed

Let me explain

$stmt->bindParam(':id', $id);

Binds the value of $id to the SQL Parameter :id and Again

$stmt->execute(array_values($result));

You are binding another parameters without any indexes.

Thus your query wants 1 parameter and you are sending two paramters.

Solution: Use one of them

Either

$stmt->bindParam(':id', $id);

Or , directly like this

$stmt->execute(array(":id" => $id));

After, that get columns from the rows and convert them into a new array in your required format

$row = $stmt->fetchAll();
//Now assuming only one was returned from the database this might work
$new = array($row[0] -> resourceName => $row[0] -> resourceURL);
May 21, 2013

URL prevent href button action php

User222914’s Question:

Hi I have a href tag where I order an array values(up to down or down to up),so my problem is that when I click twice in the same button I have no action performed.That because of in my url I have something like that:
When I click for the 1st time on my button the action is done,but I click again on the same button nothing,but when I click ‘F5’ action the action is done:
Exemple in my URL when I click one time:

http://localhost/home/test.php?dir=down&keyword=1

The second time I click the URL remains the same but no action is done.it is done when I click on F5.

My hyperlink:

echo "<a href="$_SERVER[PHP_SELF]?dir=down&keyword=$keywordkey"><img src=web/images/remove.png /></a>";

How can I resolve this ?
Thank you!!!

After you click on the button for the first time, you give command to your script to sort it downwards.

Once this action is complete, you still have same command to provide to your script i.e. down

Since it is a same command going to the your code, is does exactly same thus, the results are also same.

PHP referencing nested array values

Jpmyob’s Question:

I’m having trouble returning a value out of a nested array…

the array dump looks like this

object(myObj)#1 (3) { 
["thing1"]=> string(5) "abcde" 
["thing2"]=> string(2) "ab"
["data"]=> array(3) { 
    [0]=> string(3) "370" 
    ["id"]=> string(3) "370" 
    [1]=> string(26) "" 
    ["name"]=> string(26) "abcdefghijklmnopqrstuvwxyz" 
    [2]=> string(0) "" 
    ["address"]=> string(0) "" 
    [3]=> string(4) "wxyz" 
    ["email"]=> string(4) "wxyz"
}

I want to get to “name” inside the “data” array….

I’ve tried

echo $myObj['data']['name'];

also

echo $myObj -> $data -> $name;

they always come back as UNDEFINED.

Use

$myObj -> data['name'];

It sure is confusing. Let me explain.

The var_dump result you saw has two parts on them, one is object dump and another array .

object(myObj)#1 (3) {  <-- Starting point of object

["thing1"]=> string(5) "abcde"  <-- This is a property which has string value

["thing2"]=> string(2) "ab"     <-- This is a property which has string value


"data" here is a property of 
       object so you have to use
       $myObj -> data to access it

["data"]=> array(3) {           <-- But this is an array so you have to use 
                                    data[] to access its value
    [0]=> string(3) "370" 
    ["id"]=> string(3) "370" 
    [1]=> string(26) "" 
    ["name"]=> string(26) "abcdefghijklmnopqrstuvwxyz" 
    [2]=> string(0) "" 
    ["address"]=> string(0) "" 
    [3]=> string(4) "wxyz" 
    ["email"]=> string(4) "wxyz"
}
May 16, 2013

Create subset of php array and convert to json

Dilettante’s Question:

This is one of those that should be easy. I’m not even sure if “subset” is the right way to describe it.

My initial array looks like this:

array(3) { [0]=> array(5) { ["id"]=> string(1) "1" ["claim_id"]=> string(1) "1" ["price"]=> string(2) "50" ["date"]=> string(19) "2013-05-15 01:58:48" ["created"]=> string(19) "2013-05-15 01:58:48" } [1]=> array(5) { ["id"]=> string(2) "11" ["claim_id"]=> string(1) "1" ["price"]=> string(2) "45" ["date"]=> string(19) "2013-05-15 03:34:59" ["created"]=> string(19) "2013-05-15 03:37:01" } [2]=> array(5) { ["id"]=> string(2) "25" ["claim_id"]=> string(1) "1" ["price"]=> string(2) "50" ["date"]=> string(19) "2013-05-15 22:47:46" ["created"]=> string(19) "2013-05-15 22:52:02" } } 

I’d ultimately like to end up with just the date and price values, swap them so that date is first in the array, reformat the date, and convert it to a json array that looks something like this:

[{"date":"Mar. 15","price":"50"},{"date":"Mar. 15","price":"45"},{"date":"Mar. 15","price":"50"}] 

I ran a foreach statement to get at the data and reformat the date, then went out of my league with splice, unset, and other functions that took me in the wrong direction. Any ideas?

Create a quick function to create another array with only selected elements:

function datePriceToJson($array) {
   $a = array();
   foreach($array as $i => $a) {
      $a[] = array("date" => $a['date'], "price" => $a['price']); //Creae a new array based on the one you want
   }
   return json_encode($a);
}

datePriceToJson($array);
...

Please fill the form - I will response as fast as I can!