splitting up the path portion of a url - php

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.

Related

PHP Puttin values of array into multidimensional array

Hello I want to put values of single array into a multidimensional array with each value on a n+1
This is my array $structures
Array
(
[0] => S
[1] => S.1
[2] => S-VLA-S
[3] => SB
[4] => SB50
)
What I want for output is this
Array
(
[S] => Array(
[S.1] => Array (
[S-VLA-S] => Array (
[SB] => Array (
[SB50] => Array(
'more_attributes' => true
)
)
)
)
)
)
This is what I have tried so far
$structures = explode("\\", $row['structuurCode']);
foreach($structures as $index => $structure) {
$result[$structure][$structure[$index+1]] = $row['structuurCode'];
}
The values of the array is a tree structure that's why it would be handy to have them in an multidimensional array
Thanks in advance.
It becomes pretty trivial once you start turning it inside out and "wrap" the inner array into successive outer arrays:
$result = array_reduce(array_reverse($structures), function ($result, $key) {
return [$key => $result];
}, ['more_attributes' => true]);
Obviously a more complex solution would be needed if you needed to set multiple paths on the same result array, but this is the simplest solution for a single path.
Slightly different approach:
$var = array('a','an','asd','asdf');
$var2 = array_reverse($var);
$result = array('more_attributes' => true);
$temp = array();
foreach ($var2 as $val) {
$temp[$val] = $result;
$result = $temp;
$temp = array();
}

php multi-dimensional array provides three levels of depth instead of two

When I execute the code below:
Code:
<?php
$data = array();
$jim = array('Jim'=>1);
$bob = array('Bob'=>1);
$data['abc'][] = $jim;
$data['abc'][] = $bob;
print_r($data);
?>
I receive the following output:
Array
(
[abc] => Array
(
[0] => Array
(
[Jim] => 1
)
[1] => Array
(
[Bob] => 1
)
)
)
What I am expecting is the following output:
Array
(
[abc] => Array
(
[Jim] => 1
[Bob] => 1
)
)
How can I achieve this? To rephrase the question, how can I keep it to a single sub-array per a supplied key?
$data = array();
$jim = array('Jim'=>1);
$bob = array('Bob'=>1);
$data['abc'] = array_merge($jim, $bob);
print_r($data);
You are creating array ($data['abc']) which contains an array ([]) of arrays($jim, $bob)
It's the same as writing:
$data['abc'][0] = array('jim' => 1);
$data['abc'][1] = array('bob' => 1);
What you want is probably:
$data['abc'] = array();
$data['abc'] = array_merge($data['abc'], $jim, $bob);
Jim and Bob are array indexes by your own declaration, you have to change them first
<?php
$data = array();
$data['abc']["Jim"] =1;
$data['abc']["Bob"] = 2;
print_r($data);
?>
Demo

unique pairs storing in array in php

I am stuck at a scenerio where i need to save user input like... (in 1 go i get these reuslt)
$string = "'a':'php,'b':'.Net' ...
'c' 'java'
'c' 'php'
'c' 'java'
'a' 'php'
'a' 'java' ";
Now i need to store all these values in a database (only unique pairs).
WHat i tried so far, exploded $string with "," and stored everything in an array like
$array["a"] = "php";...but this will overwrite a = java too... //problem
I don't need to check in database that if they exist already or not..this is handled already (all dumped data in one go get a unique identifier).
All i need to do is to get unique pairs and dump into database...means
a = php, a = java, b = .net, c = java, c=php
Only solution i could see was...after exploding ...check for the pair in db against new unique identified...mysql_num_rows...if does not exist then dump else dont...
Is there any easy way...??
The best way for your purpose is to create the multidimensional array
<?php
$string = "'a':'php','b':'.Net','c':'java','c':'php','c':'java','a':'php','a':'java'";
$array = array();
$temp_arr = explode(",", $string);
foreach($temp_arr as $key=>$value)
{
list($tempkey,$tempValue) = explode(':', $value);
$tempKey = trim($tempkey,"'");
$tempValue = trim($tempValue,"'");
$array[$tempKey][] = $tempValue;
}
$array = array_map('array_unique',$array);
echo "<pre>";
print_r($array);
?>
output will be
Array
(
[a] => Array
(
[0] => php
[2] => java
)
[b] => Array
(
[0] => .Net
)
[c] => Array
(
[0] => java
[1] => php
)
)
$string = "'a':'php,'b':'.Net','c':'java','c':'php','c':'java','a':'php','a':'java'";
$temp = array_map(function($item) {
list($key, $value) = explode(':', $item);
return array(str_replace("'", "", $key) => str_replace("'", "", $value));
}, explode(",", $string));
$results = array();
foreach($temp as $item) {
$key = key($item);
if(!isset($results[$key]) || !in_array($item[$key], $results[$key])) {
$results[$key][] = $item[$key];
}
}
print_r($results);
Output:
Array
(
[a] => Array
(
[0] => php
[1] => java
)
[b] => Array
(
[0] => .Net
)
[c] => Array
(
[0] => java
[1] => php
)
)

Specifying object in PHP Array from JSON

I'm trying to use a specific object type from a JSON feed, and am having a hard time specifying it. Using the code below I grab and print the specific array (max) I want,
$jsonurl = "LINK";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json,true);
$max_output = $json_output["max"];
echo '<pre>';
print_r($max_output);
echo '</pre>';
And from the Array below, all I want to work with is the [1] objects in each array. How can I specify and get just those values?
Array
(
[0] => Array
(
[0] => 1309924800000
[1] => 28877
)
[1] => Array
(
[0] => 1310011200000
[1] => 29807
)
[2] => Array
(
[0] => 1310097600000
[1] => 33345
)
[3] => Array
(
[0] => 1310184000000
[1] => 33345
)
[4] => Array
(
[0] => 1310270400000
[1] => 33345
)
[5] => Array
(
[0] => 1310356800000
[1] => 40703
)
Well you could fetch those values with array_map:
$max_output = array_map(function($val) { return $val[1]; }, $json_output["max"]);
This requires PHP 5.3, if you use an earlier version, then you can use create_function to achieve similar results:
$max_output = array_map(create_function('$val', 'return $val[1];'), $json_output["max"]);
When you need to create new array which will contain only second values, you may use either foreach loop which will create it or use array_map() (just for fun with anonymous function available since php 5.3.0):
$newArray = array_map( function( $item){
return $item[1]
},$array);
Then you want to use last ("max" -> considering array with numeric keys) item, you can use end():
return end( $item);
And when you can process your data sequentially (eg. it's not part of some big getData() function) you can rather use foreach:
foreach( $items as $key => $val){
echo $val[1] . " is my number\n";
}
After you get $max_output...
for( $i = 0; $i < length( $max_output ); $i++ ) {
$max_output[$i] = $max_output[$i][1];
}
try this:
$ones = array();
foreach ($max_output as $r)
$ones[] = $r[1];

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