Turn string into array - php

This should be a simple task, but I guess my head is a bit overheated currently.
How do I correctly turn a GET string with the value "status[30]" into an array, like:
array ( status => 30 );
I could use something like this:
$arr = array ( 'status' => str_replace( array( 'status[', ']' ), null, $_GET['status'] ) );
but there has to be a better way.

$arr = [];
$getValue = "status[30]";
if (preg_match('#(\w+)\[(\w+)\]#', $getValue, $matches))
$arr[$matches[1]] = $matches[2];
print_r($arr);
Output:
Array
(
[status] => 30
)

Related

Store array of arrays value in one comma separated string [duplicate]

This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 7 months ago.
I have this return array
$leaseArray = Array ( [0] => Array ( [LeaseNumber] => OL/2011/0343 ) [1] => Array ( [LeaseNumber] => 184 ) [2] => Array ( [LeaseNumber] => OL/2011/0118 ) [3] => Array ( [LeaseNumber] => OL/2016/1759 ) [4] => Array ( [LeaseNumber] => OL/2013/0858 ) [5] => Array ( [LeaseNumber] => OL/2012/0535 ) [6] => Array ( [LeaseNumber] => OL/2017/2208 ) [7] => Array ( [LeaseNumber] => 2355 ) )
I want to save all the values of LeaseNumber in to one comma separated string
like $string = "OL/2011/0343 , 184 , OL/2011/0118 , OL/2016/1759"
please help me
$lease = array();
for($i=0;$i<=count($leaseArray); $i++){
$lease = $leaseArray[$i]['LeaseNumber'];
}
If you want a one-liner then this is the way
$csv = implode(' , ', array_column($a, 'LeaseNumber'));
As I said in the comments, 1 line, 2 function calls.
If you want a one-liner then this could work:
$csv = implode( ' , ', array_map( function( $a ){ return $a[ 'LeaseNumber' ]; }, $leaseArray ) );
expanded:
$csv = implode( ' , ', // step 2: implode on ' , ': space-comma-space
array_map( // step 1: pass $lease array into array_map so that we can get a new array
function( $a ){ return $a[ 'LeaseNumber' ]; }, // Accept each array in $a and only return the LeaseNumber. array_map will build a new array out of just these values
$leaseArray // the array to be processed
)
);
In essence, this is the same as:
$csv = implode( ' , ', array_column( $a, 'LeaseNumber' ) );
but array_map() allows you to transform the data before output/return if you need to.
One-liners are great but sometimes hard to read. If you want to stick with what you have here are some note
<?php
$array = array(array("LeaseNumber" => "OL/2011/0343"), array("LeaseNumber"=> 184 ), array("LeaseNumber"=> "OL/2011/0118") , array("LeaseNumber"=> "OL/2016/1759"), array("LeaseNumber"=> "OL/2013/0858"), array("LeaseNumber"=> "OL/2012/0535"), array("LeaseNumber"=> "OL/2017/2208"), array("LeaseNumber"=> 2355));
$lease = array();
//Not equal to the count it starts at 1 not 0
for($i=0;$i<count($array); $i++){
//lease is an array add to the index not overwrite
$lease[] = $array[$i]['LeaseNumber'];
}
//You needed to finish with this
$csv = implode(", ",$lease);
echo $csv;
As an fyi switch to a foreach in this case makes life easier:
$lease = array();
foreach($array as $obj){
$lease[] = $obj["LeaseNumber"];
}

PHP Array Separation

I am having a few issues with an array being brought from a database.
The original array once converted looks like this:
Array
(
[0] => {"lastTimeSave":"1494000000"
[1] => "rankexpire":"0"
[2] => "evocity_rank":"g-vip"
[3] => "evocity_rankexpire":"0"}
)
I successfully removed some unuseful characters so my final array looks like this:
Array
(
[0] => lastTimeSave:1494000000
[1] => rankexpire:0
[2] => evocity_rank:g-vip
[3] => evocity_rankexpire:0
)
What I am wanting to do is get everything before the ':' and place it into the key of the array, then remove the ':' so it looks something like this:
Array
(
['lastTimeSave'] => 1494000000
['rankexpire'] => 0
['evocity_rank'] => g-vip
['evocity_rankexpire'] => 0
)
I am separating using:
$staffarray = str_replace('"', "", $staffarray);
$staffarray = str_replace('{', "", $staffarray);
$staffarray = str_replace('}', "", $staffarray);
I have already tried multiple things, including:
foreach ($stafftestarray as $key => $value) {
$substring = substr($value, 0, strpos($value, ';'));
$subsubstring = str_replace($substring, "", $value);
$value = $subsubstring;
}
However nothing seems to change it and the output is not being changed, I would really appreciate any help I can get with this problem as I have searched for countless hours how to fix it to no avail.
Looks like an exploded json object stored as on array.
Though I'm not sure why your data looks like that (did you explode the string by , ?)
This will do what you want:
$data = json_decode(implode(',', $yourArray), true);
Don't remove the " 's and use explode to create a new array based on your old array.
$array = array
(
0 => "lastTimeSave:1494000000",
1 => "rankexpire:0",
2 => "evocity_rank:g-vip",
3 => "evocity_rankexpire:0"
);
$new_array = array();
foreach($array as $value)
{
$item = explode(":", $value);
$new_array[$item[0]] = $item[1];
}
print_r($new_array);
Where print_r($new_array) will give:
Array
(
[lastTimeSave] => 1494000000
[rankexpire] => 0
[evocity_rank] => g-vip
[evocity_rankexpire] => 0
)

How to make an array of this string?

I have a string like this:
$str = '"list":["test 1","test 2"]';
How to make an array:
$arr['list'] = array('test 1','test 2');
?
Make it a valid JSON string and use json_decode function like this:
$str = '"list":["test 1","test 2"]';
$arr = json_decode('{' . $str . '}', true);
print_r($arr);
OUTPUT:
Array
(
[list] => Array
(
[0] => test 1
[1] => test 2
)
)

splitting up the path portion of a url

i couldn't find anything so i just wanted to take a url and then split it and turn it into key value pairs.
$url = 'http://domain.com/var/1/var2/2';
i am currently using a array_chunk on the path after using a parse_url
$u = parse_url($url);
$decoded = array_chunk($u['path'],2);
but it returns
array (
[0] => array (
[0] => var
[1] => 1
),
[1] => array (
[0] => var2
[1] => 2
)
)
what i would like is
array (
[var] => 1,
[var2] => 2
)
is there a Zend Framework method that is available to decode this into an array?
I'd use request object.
$url = 'http://domain.com/var/1/var2/2';
$request = new Zend_Controller_Request_Http($url);
$params = $request->getParams();
// or
$param = $request->getParam('var', $defaultValueNull);
This has the advantage, that you don't have to use isset to check which keys were set.
$u = parse_url($url);
$decoded = array_chunk($u['path'],2);
$new = array();
for ($decoded as $pair) {
$new[$pair[0]] = $pair[1];
}
print_r($new);
outputs
array (
[var] => 1,
[var2] => 2
)
If you're in the Controller it's simply
$data = $this->_getAllParams();
unset($data['module'], $data['controller'], $data['action']);
$data will now be
array (
[var] => 1,
[var] => 2
)
Hopefully you're not POSTing variables as well or this will also include the POST'd variables.

Access array in PHP

How do I access the following array in PHP:
$Record = Array ( [0] => 1 [1] => 1 [2] => 1);
I have tried
echo $Record[0];
But no luck :(
To initialize an array (you don't need an associative array, if your keys are just the actual indices) use:
$record = array(1, 1, 1);
Then you can access the first element via:
$first = $record[0];
Try
$Record = array( 0 => 1, 1 => 1, 2 => 1);
or even
$Record = array(1,1,1);
and then
echo $Record[0];
Keep in mind that print_r shows you some form of representation of the array. so this code:
$record1 = array(1,1,1);
print_r($record1);
will output:
Array
(
[0] => 1
[1] => 1
[2] => 1
)
$Record = Array ( 1, 1, 1 );
your array has wrong syntax
just a guess, but you can try something like that:
$pattern = "|\[(\d+)\] => (\d+)|";
preg_replace_callback(
$pattern,
"add_to_array",
$text);
and write a function 'add_to_array' to add to your array, get the index by $matches[1] and the value by $matches[2]!

Categories