I have an array containing single key objects like so:
Array
(
[0] => stdClass Object
(
[state] => 1
)
[1] => stdClass Object
(
[state] => 1
)
)
I want it to look like this:
Array
(
[0] => 1
[1] => 1
)
What is the most efficient way of doing this? I'm not quite sure how to put this problem in simple words, so I can't google it either.
You could use array_map:
$result = array_map(function($object) {
return $object->state;
}, $originalArray);
you can do it with a for loop :
for $array in $val
$val =$val[state]
You can use array_walk and pass the value in by reference:
array_walk($array, function(&$v, $i) {
$v = $v->state;
});
or
array_walk($array, create_function('&$v', '$v = $v->state;'));
If you got one of the newer PHP versions you can do that with a foreach loop and a reference:
foreach ($array as &$value)
{
$value = $value->state;
}
Related
How can I count in a multidimensional array the number of element with a special condition ?
Array
(
[0] => Array
(
[item] => 'Banana'
)
[1] => Array
(
[item] => 'Banana'
)
[2] => Array
(
[item] => 'Cherry'
)
[3] => Array
(
[item] => 'Apple'
)
)
For example, for this array I should find 2 for Banana.
Si I tried:
$i=0;
foreach($array as $arr) {
if($arr[item]=='Banana') { $i++; }
}
Is there a better solution please ?
Thanks.
Method 1:
Using built-in functions - array_column and array_count_values:
print_r(array_count_values(array_column($arr,'item')));
Method 2:
Using foreach with simple logic of making your fruit as key and its count as value:
$arr = [
["item"=>"Banana"],
["item"=>"Banana"],
["item"=>"Cherry"],
["item"=>"Apple"]
];
$countArr = [];
foreach ($arr as $value) {
$item = $value['item'];
if(array_key_exists($item, $countArr)) // If key exists, increment its value
$countArr[$item]++;
else // Otherwise, assign new key
$countArr[$item] = 1;
}
print_r($countArr);
Final result in both case would be:
Array
(
[Banana] => 2
[Cherry] => 1
[Apple] => 1
)
So when you want Banana's count, you can get it like this:
echo $countArr['Banana'];
Use array_count_values(), it is pretty straight forward:
foreach($array as $arr) {
$new[] = $arr['item'];
}
print_r(array_count_values($new));
On a side note, there isn't anything wrong with your approach, unless you want to count all values. Also on a side note, I think you'll find a foreach() will eek out a slightly faster time than array_column(), especially on a large array.
I am working on a big script which will generate some string or array or multidimensional array i want use mysql_real_escape_string for all array / string
for that this i tried the below code
function check($data) {
if(!is_array($data)) {
return mysql_real_escape_string($data);
} else if (is_array($data)) {
$newData = array();
foreach($data as $dataKey => $dataValue){
if(!is_array($dataValue)){
$key = mysql_real_escape_string($dataKey);
$value = mysql_real_escape_string($dataValue);
$newData[$key] = $value;
}
}
return $newData;
}
}
if i use like this check('saveme'); this returns value
if i pass a array it returns corrent value [ check(array('a','b','c',1,2,3)) ]
if i pass multidimensional array i get [check(array(array('a',array('a','b','c',1,2,3),'c',1,2,3),'b',array('a','b','c',1,2,3),1,2,3))]
A kind note i want to use mysql_real_escape_string for array key too.
You can use array_walk_recursive function, to go throw all leaves of the array, and escape values:
array_walk_recursive($array, function(&$leaf) {
if (is_string($leaf))
$leaf = mysql_real_escape_string($leaf);
});
Also, it is good to follow data consistency rules, and do not use !is_array(), but is_string(), because mysql_real_escape_string takes string params, not !string.
Unfortunately, array_walk_recursive is designed so, that it can't edit keys. If you need edit keys, you may want to write your own recursive function. I don't want to copy answer, you can find it here
You can use this function :
(MyStringEscapeFunc() is your custom escape function)
function escape_recursive($arr){
if(is_array($arr)){
$temp_arr = array();
foreach ($arr as $key=>$value){
$temp_arr[MyStringEscapeFunc($key)] = escape_recursive($value);
}
return $temp_arr;
}else{
return MyStringEscapeFunc($arr);
}
}
Example Result :
//Before :
Array (
[0] => Array (
[0] => foo'bar
[1] => bar'baz
)
[1] => foob'ar
[2] => Array ( [foo'baz] => baz'foo )
)
//After :
Array (
[0] => Array (
[0] => foo\'bar
[1] => bar\'baz
)
[1] => foob\'ar
[2] => Array ( [foo\'baz] => baz\'foo )
)
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];
Hello all,
Array (
[0] => Array ( [id] => 242)
[1] => Array ( [id] => 24)
[2] => Array ( [id] => 234)
[3] => Array ( [id] => 244)
)
Array (
[0] => 24
[1] => 242
[2] => 244
)
When I used print_r(), I got above two arrays. Now, I need to filter two arrays and get uncommon values so my output will be 234
I would guess you mean array_diff, which returns you the set of elements that only exists in one of the arrays. You might have to run it twice however, if you don't know which array is the superset:
$diff = array_merge(array_diff($a1, $a2), array_diff($a2, $a1));
Oh and if the first array is nested like that, convert it first into a value list with $a1 = array_map("current", $a1) or something.
do a a foreach to go through the array, and then use something like in_array to do a test to see if any of the keys within the first array exists
$array3 = array();
foreach ($array1 as $v)
{
if !(in_array($v['ID'], $array2))
{
$array3[] = $v;
}
}
$array3 = array_unique($array3);
$array3 will return a list of non existant ID's (that didn't exist in $array2)
create two arrays with simply all the values in them, and then do
$arrayResult = $array1;
foreach($array1 as $id => $val) {
if !isset($array2[$id]) {
$arrayResult[] = $id;
}
}
foreach($array2 as $id => $val) {
if !isset($array1[$id]) {
$arrayResult[] = $id;
}
}
and then $arrayResult will have all uncommon values!
I have a multidimensional array, the sub-arrays consist of further values, I would like for all sub-arrays that only have one value to be converted into a string. How can I successfully scan through a multidimensional array to get the result?
Below is a small section of the array as it is now.
[1] => Array
(
[name] => Array
(
[0] => Person's name
)
[organisation] => Array
(
[0] => This is their organisation
[1] => aka something else
)
[address] => Array
(
[0] => The street name
[1] => The town name
)
[e-mail] => Array
(
[0] => test#this.site.com
)
)
and here is how I would like it to end up
[1] => Array
(
[name] => Person's name
[organisation] => Array
(
[0] => This is their organisation
[1] => aka something else
)
[address] => Array
(
[0] => The street name
[1] => The town name
)
[e-mail] => test#this.site.com
)
This should do the trick.
function array2string(&$v){
if(is_array($v) && count($v)==1){
$v = $v[0];
}
}
array_walk($array, 'array2string');
Or as a one-liner, since I'm nuts.
array_walk($array, create_function('&$v', 'if(is_array($v) && count($v)==1){$v = $v[0];}'));
EDIT: It looks like that array is an element in a bigger array. You need to put this function inside of a foreach loop.
function array2string(&$v){
if(is_array($v) && count($v)==1){
$v = $v[0];
}
}
foreach($array as &$val){
array_walk($val, 'array2string');
}
Or using my crazy create_function one-liner.
foreach($array as &$val){
array_walk($val, create_function('&$v', 'if(is_array($v) && count($v)==1){$v = $v[0];}'));
}
This should work no matter how deep the array is.
Put this function in your code:
function array2string(&$v){
if(is_array($v)){
if(count($v, COUNT_RECURSIVE) == 1){
$v = $v[0];
return;
}
array_walk($v, 'array2string');
}
}
Then do this:
array_walk($array, 'array2string');
This PHP 5.3 code uses a closure. You can use a named function, too, if you want. It specifically checks for strings, and calls itself for nested arrays.
<?php
array_walk($array, $walker = function (&$value, $key) use (&$walker) {
if (is_array($value)) {
if (count($value) === 1 && is_string($value[0])) {
$value = $value[0];
} else {
array_walk($value, $walker);
}
}
});