How i can access this php array string value - php

array(3) {
[20]=>
string(43) "{"shortname":"testvqweq","fullname":"test"}"
[21]=>
string(51) "{"shortname":"bwqbdwqbwqeb","fullname":"qwbdwqbwq"}"
[22]=>
string(48) "{"shortname":"wqdwqdwqdw","fullname":"dwqwqdwq"}"
}
I want to access shortname, fullname from array like:
Testvqweqe test

Here is an example that will clear things up for you I hope:
<?php
$array = [
"20" => '{"shortname":"testvqweq","fullname":"test"}',
"21" => '{"shortname":"bwqbdwqbwqeb","fullname":"qwbdwqbwq"}',
"22" => '{"shortname":"wqdwqdwqdw","fullname":"dwqwqdwq"}',
];
echo '<pre>';
print_r($array);
foreach($array as $json){
echo '<pre>';
$j2a = json_decode($json,true);
print_r($j2a['shortname']);
}
$j2a1 = json_decode($array[20],true)['fullname']; /*grab the value in the same line as the json_decode */
echo '<pre>';
echo "j2a1: ";
print_r($j2a1); /* Could have used an echo :) */
Will return:
Array
(
[20] => {"shortname":"testvqweq","fullname":"test"}
[21] => {"shortname":"bwqbdwqbwqeb","fullname":"qwbdwqbwq"}
[22] => {"shortname":"wqdwqdwqdw","fullname":"dwqwqdwq"}
)
testvqweq
bwqbdwqbwqeb
wqdwqdwqdw
j2a1: test
I dumbed it down on purpose and did not use one lines to show how you turn the json in the array into an array and print the value you like from that one... and at the end I gave an example of a one liner without a loop.

You could simple access them with a foreach
foreach(array as arrayIndex)
{
$shortName = arrayIndex['shortname'];
$fullName= arrayIndex['shortname'];
}
if you need to use the variables you will want to do that action within the foreach loop as well or alternatively you will want to store them outside the foreach loop.
GL.

Related

Get an EXACT value in $_POST array

I'm studying php and I'm trying to figure out how to get the string "Juve_Milan" from this var_dump($_POST) :
array(5) {
["Juve_Milan"] => array(2) {
[0] => string(1)
"5" [1] => string(1)
"1"
}["Inter_Roma"] => array(2) {
[0] => string(1)
"4" [1] => string(1)
"4"
}["Napoli_Lazio"] => array(2) {
[0] => string(1)
"2" [1] => string(1)
"5"
}["name"] => string(0)
"" ["submit"] => string(5)
"Invia"
}
I could get all of them with:
foreach ($_POST as $param_name => $param_val) {
echo "<tr><td>".$param_name."</td><td>".$param_val[0]."-".$param_val[1]."</td></tr>";
}
But i want to get them exactly one by one, for example, if i want to get the string "Juve_Milan" or "inter_Roma" how can i do?
Without looping, how can i get the string value: "Juve_milan" or "Inter_Roma"? Becouse with the loop i can access them this way : $_POST as $param_name => $param_val
But i want to get them without loop, my first attempt was something like $_POST[0][0] but its wrong...
There are numbers of php array functions you can use.
You can use
array shift
to remove an element from an array and display it .e.g
$club = ['juve_millan', 'inter_roma', 'napoli_lazio'];
$juve = array_shift($club);
echo $juve;// 'juve_millan'
but note that the array is shortened by one element i.e. 'juve_millan' is no more in the array and also note that using
array_shift
over larger array is fairly slow
Array Slice function
PHP
array_slice()
function is used to extract a slice of an array e.g
$club = ['juve_millan', 'inter_roma', 'napoli_lazio'];
if I want to display
inter_roma
or assigned it to a variable, then I can do this
$roma = array_slice($club, 1, 1);// The first parameter is the array to slice, the second parameter is where to begin(which is one since most programming language array index start from 0 meaning juve_millan is zero, while inter_roma is 1, napoli_lazio is 2) and the length is 1 since i want to return a single element.
I hope you understand
You could iterate over keys of the main array like this:
foreach($_POST as $param_name => $param_val) {
echo "<tr><td>".$param_name."</td></tr>";
}
This will return each Juve_Milan, Inter_Roma etc. one by one. Although it's part of the code you already have, I believe this will return values you want only.

PHP how to echo array values which have no name attached to them

How can I put each value into a variable?
I tried using foreach but I am not sure what to put in the ??? area
I tried also using echo $results[14], but I received an undefined error.
foreach($results['ups'] as $result) {
echo $result['???']. '<br>';
}
output:
array(1) {
["ups"]=> array(4) {
[14]=> string(5) "62.89"
["01"]=> string(5) "30.47"
["02"]=> string(5) "20.76"
[11]=> string(5) "20.96"
}
}
Array
(
[ups] => Array
(
[14] => 62.89
[01] => 30.47
[02] => 20.76
[11] => 20.96
)
)
You put nothing in the []:
foreach($results['ups'] as $result) {
echo $result + '<br>';
}
should do it.
array_keys() should return all defined keys, so try eg.
$keys = array_keys($results['ups']);
echo $results['ups'][$keys[0]];
echo $results['ups'][$keys[1]];
to access the first and second element.
simply use
echo $results['ups']['14'];
if you don't know the index that you want to access or maintaining key index is not relevant.
sort $results['ups'];
echo $results['ups'][0];

Add text to each element of array

Basically what I am trying to do is add text before (and after) each element of an array. This is an example:
<?php
$word="code";
$chars=preg_split('//', $word, -1, PREG_SPLIT_NO_EMPTY);
print"<pre>";
print_r($chars);
print"</pre>";
?>
(Yes I need the regex so I can't just use str_split())
which outputs:
Array
(
[0] => c
[1] => o
[2] => d
[3] => e
)
Now my ultimate goal is to get the final string to be something like:
"shift+c","shift+o","shift+d","shift+e"
If I can get help just adding the "shift+ in front of each element, then I can use implode() to do the rest.
Here's a solution based on my comments:
$word = 'code';
$result = array_map(function($c){ return "shift+$c"; }, str_split($word));
And here's the output var_dump($result):
array(4) {
[0]=> string(7) "shift+c"
[1]=> string(7) "shift+o"
[2]=> string(7) "shift+d"
[3]=> string(7) "shift+e"
}
Edit: If you really need to you can use the result from preg_split as the array in array_map.
You can loop through the chars array and concatenate your desired string.
<?php
$word="code";
$chars=preg_split('//', $word, -1, PREG_SPLIT_NO_EMPTY);
foreach($chars as $c){
echo "shift+" . $c . " ";
}
?>
Outputs:
shift+c shift+o shift+d shift+e

PHP foreach subarray in array

I'm trying to parse an array that looks like this:
array(1) {
["StrategischeDoelstellingenPerDepartement"] => array(412) {
[0] => array(5) {
["CodeDepartement"] => string(8) "DEPBRAND"
["NummerHoofdstrategischeDoelstelling"] => string(1) "1"
["Nummer"] => string(2) "27"
["Titel"] => string(22) "DSD 01 - HULPVERLENING"
["IdBudgetronde"] => string(1) "2"
}
[1] => array(5) {
["CodeDepartement"] => string(8) "DEPBRAND"
["NummerHoofdstrategischeDoelstelling"] => string(1) "2"
["Nummer"] => string(2) "28"
["Titel"] => string(24) "DSD 02 - Dienstverlening"
["IdBudgetronde"] => string(1) "2"
}
[2] => array(5) {
["CodeDepartement"] => string(8) "DEPBRAND"
["NummerHoofdstrategischeDoelstelling"] => string(1) "2"
["Nummer"] => string(2) "29"
["Titel"] => string(16) "DSD 03 - KLANTEN"
["IdBudgetronde"] => string(1) "2"
}
...
(The array goes on but it's too big to post it here in its entirety)
I can do a foreach loop on the array like this:
foreach($my_arr->StrategischeDoelstellingenPerDepartement as $row){
echo "i found one <br>";
}
However, I want to do the same thing on other arrays and I want to make the function generic. The first key (StrategischeDoelstellingenPerDepartement in this case) can sometimes change, which is why I'd like to do it generically. I've already tried the following:
foreach($my_arr[0] as $row){
echo "i found one <br>";
}
But then I get the following notice, and no data:
Notice: Undefined offset: 0 in C:\Users\Thomas\Documents\GitHub\Backstage\application\controllers\AdminController.php on line 29
This is probably a silly question, but I'm new to PHP and this seemed like the right way to do it. Obviously, it isn't. Can anyone help me out, please?
Use reset to grab the first element of $my_arr without knowing the key name:
$a = reset($my_arr);
foreach($a as $row){
echo "i found one <br>";
}
Shift the sub-array off the main array and loop over it:
$sub = array_shift($my_arr);
foreach ($sub as $row) {
echo $row['Titel'], "<br>";
}
You are trying to do is object, not array $my_arr->StrategischeDoelstellingenPerDepartement.
You could use isset() to check the index existence:
if(isset($my_arr['StrategischeDoelstellingenPerDepartement'])){
foreach($my_arr['StrategischeDoelstellingenPerDepartement'] as $row){
echo "i found one <br>";
}
}
Or, you could use array_values() to ignore the array keys and to make it an index array:
$my_new_arr = array_values($my_arr);
foreach($my_new_arr as $row){
echo "i found one <br>";
}
Use current ref : http://in3.php.net/manual/en/function.current.php
$a = current($my_arr);
foreach($a as $row){
echo "i found one <br>";
}

How to randomize an array of objects in PHP?

I have this example of an array of objects and I need to randomize it each time I do a foreach loop.
Looks like shuffle works only on arrays.
One thing is that I cant convert this into an array, because then it will become a STD object which I can't use, because of the way my mapper works.
array(48) {
[0] => object(Friends_Model_Friends)#142 (4) {
["_id":protected] => NULL
["_tal":protected] => object(stdClass)#194 (3) {
["thumb"] => object(stdClass)#196 (6) {
["id"] => string(8) "10884697"
["type"] => string(1) "2"
["gallery"] => string(1) "1"
}
}
["_friend":protected] => string(7) "3492149"
["_dependent_table":protected] => NULL
}
[1] => object(Friends_Model_Friends)#195 (4) {
["_id":protected] => NULL
["_tal":protected] => object(stdClass)#143 (3) {
["thumb"] => object(stdClass)#202 (6) {
["id"] => string(8) "11160632"
["type"] => string(1) "2"
["gallery"] => string(1) "1"
}
}
["_friend":protected] => string(7) "3301541"
["_dependent_table":protected] => NULL
}
....
Any ideas on shuffling this?
edit: Zend_Debug::dump(shuffle($object)); returns bool(true)
<?php
$my_array;
echo '<pre>'; print_r($my_array); echo '</pre>';
shuffle ($my_array);
echo '<pre>'; print_r($my_array); echo '</pre>';
?>
Try this code
But the objects are in an array, not another object so you can use shuffle...
Shuffle always returns a boolean:
bool shuffle ( array &$array )
So you can't return it like
return shuffle( $myAwesomeArray );
This is what I just did and I wondered why it didn't give anything back, as you're probably expecting your shuffled array back.
You just have to call it like this
shuffle( $myAwesomeArray );
return $myAwesomeArray;
And all should work just fine.

Categories