I would like to change values in an array. Here is my starting array:
Array
(
[0] => Array
(
[name] => aaa
)
[1] => Array
(
[name] => bbb
)
[2] => Array
(
[name] => ccc
)
)
I declare a searchterm (eg. "aaa") and a new name for it (eg. "test"). And than I do a str_replace to actually change it.
Unfortunately nothing changes nor do I get an error message. Can you please help and tell me where my error is please?
for ($i=0; $i < count($json) ; $i++) {
$search = $old_name;
$replace = $new_name;
str_replace($search, $replace, $json[$i]['name']);
print_r($json);
}
As the documentation says, this function doesn't update the array
This function returns a string or an array with the replaced values.
you need to update it with the returned value:
for ($i=0; $i < count($json) ; $i++) {
$search = $old_name;
$replace = $new_name;
$json[$i]['name'] = str_replace($search, $replace, $json[$i]['name']);
print_r($json);
}
str_replace returns a string. I think you are trying to use it as though it alters a parameter that was passed by reference. Instead you should assign the returned value to the array at the correct index.
for ($i=0; $i < count($json) ; $i++) {
$search = $old_name;
$replace = $new_name;
$json[$i]['name'] = str_replace($search, $replace, $json[$i]['name']);
print_r($json);
}
If you want to replace/change more than one name, I suggest you to use the below code.
// define an array with keys as new name and value as old name ( name to be replaced).
$change_name_array= array('test'=>'aaa','another_test'=>'bbb');
// loop the array
for ($i=0; $i < count($json) ; $i++) {
// check if the name is in defined array
if(in_array($json[$i]['name'],$change_name_array)){
// get the key and replace it.
$json[$i]['name'] = array_search($json[$i]['name'], $change_name_array);
}
}
Out put: here aaa id replaced with test and bbb is replaced with another_test
Array
(
[0] => Array
(
[name] => test
)
[1] => Array
(
[name] => another_test
)
[2] => Array
(
[name] => ccc
)
)
Related
I've the following variable that is dinamically created:
$var = "'a'=>'123', 'b'=>'456'";
I use it to populate an array:
$array=array($var);
I can't do $array=array('a'=>'123', 'b'=>'456') because $var is always different.
So it shows me:
Array
(
[0] => 'a'=>'123', 'b'=>'456'
)
This is wrong, 'cause I need to get:
Array
(
[a] => 123
[b] => 456
)
What is wrong on my code?
Thanks in advance.
Ideally you should just leverage PHP's syntax to populate an associative array, something like this:
$array = [];
$array['a'] = '123';
$array['b'] = '456';
However, you could actually write a script which parses your input to generate an associate array:
$var = "'a'=>'123', 'b'=>'456'";
preg_match_all ("/'([^']+)'=>'([^']+)'/", $var, $matches);
$array = [];
for ($i=0; $i < count($matches[0]); $i++) {
$array[$matches[1][$i]] = $matches[2][$i];
}
print_r($array);
This prints:
Array
(
[a] => 123
[b] => 456
)
I have a Laravel installed with Moloquent (Mongo). Mongo ins't necessarily the problem, when the model loads the "JSON" record, it becomes a PHP associative array.
I need to be able to create a function in a model that returns an array element by a string.
for example:
$search1 = 'folder1/folder2/folder3/item';
//would look like: $array['folder1'][folder2'][folder3']['item']
$search2 = 'folder1/picture1/picture';
//would look like: $array['folder1'][picture1']['picture']
echo getRecord($search1);
echo getRecord($search2);
function getRecord($str='') {
//this function take path as string and return array
return $result;
}
I guess I could use the ?? operator, but I have to form an array "check" meaning:
How would I form the $array['1']['2']['3'] if I have 3 elements deep or 1 ($array['1']), or 5 ($array['1']['2']['3']['4']['5']).
I am making an api to add an item or folder to Mongo.
Input : "f1/f2/item"
This function I have:
echo print_r($j->_arrayBuilder('f1/f2/item'), true);
public function _arrayBuilder($folderPath)
{
$ret = array();
$arr = explode('/', $folderPath);
Log::info("Path Array:\n" . print_r($arr, true));
$x = count($arr) - 1;
Log::info("Count: " . $x);
for ($i = 0; $i <= $x; $i++) {
Log::info("Element of arr: " . $arr[$i]);
$ret = array($arr[$i] => $ret);
}
return $ret;
}
Current output:
Array
(
[item] => Array
(
[f2] => Array
(
[f1] => Array
(
)
)
)
)
Desire output:
Array
(
[f1] => Array
(
[f2] => Array
(
[item] => Array
(
)
)
)
)
Note: I have tried PHP's array_reverse and it does not work on this.. Multidimensional and non-numeric..
Thank you.
If I understand correctly, You want to take input string f1/f2/f3/f4/f5/item and create array("f1" => array("f2" => array("f3" => array("f4" => array("f5" => array("item" => array()))))))
In order to do that you can use function close to what you tried as:
function buildArr($path) {
$path = array_reverse(explode("/", $path)); // getting the path and reverse it
$ret = array();
foreach($path as $key)
$ret = array($key => $ret);
return $ret;
}
For input of print_r(buildArr("f1/f2/item")); it prints:
Array
(
[f1] => Array
(
[f2] => Array
(
[item] => Array
(
)
)
)
)
Hope that what you meant. If not feel free to comment
I have the following code:
$nameArray = array("Bob", "John", "Ben", "Mike");
for ($i = 0; $i < count($nameArray); $i++){
$name = $nameArray[$i];
$nameArray[$name] = strlen($nameArray[$i]);
echo $nameArray[$i]."'s name is ".$nameArray[$name]." letters long <br>";
}
Why is count($nameArray) returning 8 instead of 4?
You change the size of the array in the loop by pushing new Values into it. That's why
When you have declare array that time it is having numeric indexes as
Array ( [0] => Bob [1] => John [2] => Ben [3] => Mike )
After that you are pushing new values with new index using following statement:
$nameArray[$name] = strlen($nameArray[$i]);
and it is creating array like :
Array ( [0] => Bob [1] => John [2] => Ben [3] => Mike [Bob] => 3 [John] => 4 [Ben] => 3 [Mike] => 4)
Thats why it is showing count as 8
Create new array instead of using same array
$nameArray = array("Bob", "John", "Ben", "Mike");
$nameLength = array();
for ($i = 0; $i < count($nameArray); $i++){
$name = $nameArray[$i];
$nameLength[$name] = strlen($nameArray[$i]);
echo $nameArray[$i]."'s name is ".$nameLength[$name]." letters long <br>";
}
$nameArray[$name] = strlen($nameArray[$i]);
is the reason why you array length doubled. You add the the element length as new elements to the array. So it's length doubled.
May be you want a new array to store it's length with
$nameLen[$name] = strlen($nameArray[$i]);
Hello I have an array that consists of two other arrays within it using the following code:
foreach($relations as $rel){
$data[$i]["relationTo"] = $rel["name"];
$data[$i]["relation"] = $rel["relation"];
$i = $i+1;
}
foreach($relations as $rel){
$children[$i]["id"] = $rel["id2"];
$children[$i]["name"] = $rel["sname"];
$children[$i]["data"] = $data;
$i = $i+1;
}
foreach($relations as $rel){
$relationArray[$i]["id"] = $rel["id"];
$relationArray[$i]["name"] = $rel["name"];
$relationArray[$i]["children"] = $children;
$i = $i+1;
}
When I print this out using:
print_r($relationArray);
It prints the following:
Array ( [2] => Array ( [id] => 4 [name] => Albaraa [children] =>
Array ( [1] => Array ( [id] => 5 [name] => Sadi [data] =>
Array ( [0] => Array ( [relationTo] => Albaraa [relation] => Father ) ) ) ) ) )
I am using json_encode and I need it to be output in json a certain way not including the indexed count of arrays in the beginning...the json output when I use:
echo json_encode($relationArray);
is like this currently:
{"2":{"id":"4","name":"Albaraa","children":
{"1":{"id":"5","name":"Sadi","data": [{"relationTo":"Albaraa","relation":"Father"}]}}}}
With the "2" and "1" in front of what the first 2 arrays are...which is not what I am trying to achieve which would be like this:
{"id":"4","name":"Albaraa","children":
{"id":"5","name":"Sadi","data": [{"relationTo":"Albaraa","relation":"Father"}]}}}}
Any help will be much appreciated!
Several solutions
1) Do not enter values by [$i], prepare new complete inner array and put it inside with array_push
2) If you still want to do this way you can extract just the values:
print_r(json_encode(array_values($array)));
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];