PHP array manipulation - php

I have an array as $arr = array("name" => "Fom Xong" , "Sales" => "100");
From this array I want to generate a string something like this
$str = 'name="Fom Xon" Sales="100"';
Is it possible???
thanks in advance

For example you can do like this:
$tmp_arr = array();
foreach ($arr as $key => $val)
$tmp_arr[] = $key.'="'.$val.'"';
$str = implode(' ', $tmp_arr);

$output = array();
foreach ($arr as $key => $value) {
$output[] = "$key=\"$value\"";
}
echo join(' ', $output);
Or:
echo join(' ', array_map(function ($key, $value) { return "$key=\"$value\""; }, array_keys($arr), $arr));

Related

Merging two foreach in php laravel/api

Good day! i had success in finding answers that shortens my code. Someone said that i can merge the foreach statements for it to become even shorter. but i searched everywhere but cant seem to find any solution with similar codes that i have. I just want to know how can i merge the two foreach.
here is my code:
$newArray = [];
$keys = ['name', 'sex', 'age', 'height', 'weight'];
foreach(explode(PHP_EOL, Storage::get('upload/test.txt')) as $key => $line) {
$finalArray = [];
foreach( explode(',', $line) as $i => $value){
$finalArray[ $keys [ $i ] ] = $value;
}
array_push($newArray, $finalArray);
}
die(json_encode($newArray));
here is another code with the same output as the first code:
$newArray = array();
foreach(explode(PHP_EOL, Storage::get('upload/test.txt')) as $key => $line) {
array_push($newArray, explode(',', $line));
}
$finalArray = array();
foreach($newArray as $key) {
$key = [
"name" => $key[0],
"sex" => $key[1],
"age" => $key[2],
"height" => $key[3],
"weight" => $key[4],
];
array_push($finalArray, $key);
}
die(json_encode($finalArray));
You could make it simpler by using array_combine:
$newArray = [];
$keys = ['name', 'sex', 'age', 'height', 'weight'];
foreach (explode(PHP_EOL, Storage::get('upload/test.txt')) as $line) {
$newArray[] = array_combine($keys, explode(',', $line));
}
Or you could use array_map() and do something like:
$keys = ['name', 'sex', 'age', 'height', 'weight'];
$newArray = array_map(function ($line) use ($keys) {
return array_combine($keys, explode(',', $line));
}, explode(PHP_EOL, Storage::get('upload/test.txt')));

How to convert PHP array

I have an array like this one:
array( array("key1" => "value1"), array("key2" => "value2"), ... )
I need to convert it to this format:
array( "value1", "value2", ... )
How can I do it using PHP?
Looping would be acceptable in this case. If you do want an example without looping, you can use array_map but I don't think it would be more "clear and simple":
$array = array_map(function($value) {
return reset($value);
}, $array);
This function SHOULD (untested) return a single array with no associative keys from your mufti-dimentional array.
function single_array ($array) {
$array2 = array();
if (is_array($array)) {
foreach ($array as $key => $val) {
if (is_array($val)) {
$array2[] = single_array($val);
}else{
$array2[] = $val;
}
}
}
return $array2;
}
$array = single_array($array);

Split a string into keys of associative arrays (PHP)

Do you have an idea, how can a string be converted to a variable, e.g.
there is a string -> $string = 'one|two|three';
there is an array -> $arr = array('one' => array('two' => array('three' => 'WELCOME')));
I want to use all with explode(); exploded values to access the array $arr. I tried this code:
$c = explode('|', $string);
$str = 'arr[' . implode('][', $c) . ']';
echo $$str;
It doesnt work, sadly :( Any ideas?
You're doing it wrong.
You can do what you want with a loop to go through the array level by level
$string = 'one|two|three';
$arr = array('one' => array('two' => array('three' => 'WELCOME')));
$c = explode('|', $string);
$result = $arr;
foreach($c as $key)
$result = $result[$key];
echo $result; // WELCOME
Here's a sort of recursive function:
$ex_keys = array('one', 'two', 'three');
$ex_arr = array('one' => array('two' => array('three' => 'WELCOME')));
function get_recursive_var($keys, $arr) {
if (sizeof($keys) == 1)
return $arr[$keys[0]];
else {
$key = array_shift($keys);
return get_recursive_var($keys, $arr[$key]);
}
}
var_dump(get_recursive_var($ex_keys, $ex_arr));

how to get associative array from string

I have one string like:-
$attributes = "id=1 username=puneet mobile=0987778987 u_id=232";
Now, I want to get it in following associative array format:-
$attributes{'id' => 1, 'username' => puneet, 'mobile' => 0987778987, 'u_id' => 232}
Note:- These all values are separated by space only. Any help will be appreciable.
Thanks in advance
$final_array = array();
$kvps = explode(' ', $attributes);
foreach( $kvps as $kvp ) {
list($k, $v) = explode('=', $kvp);
$final_array[$k] = $v;
}
I can suggest you to do it with a regular expression:
$str = "id=1 username=puneet mobile=0987778987 u_id=232";
$matches = array();
preg_match_all( '/(?P<key>\w+)\=(?P<val>[^\s]+)/', $str, $matches );
$res = array_combine( $matches['key'], $matches['val'] );
working example in phpfiddle
$temp1 = explode(" ", $attributes);
foreach($temp1 as $v){
$temp2 = explode("=", $v);
$attributes[$temp2[0]] = $temp2[1];
}
EXPLODE
this code will solve your problem.
<?php
$attributes = "id=1 username=puneet mobile=0987778987 u_id=232";
$a = explode ( ' ', $attributes) ;
$new_array = array();
foreach($a as $value)
{
//echo $value;
$pos = strrpos($value, "=");
$key = substr($value, 0, $pos);
$value = substr($value, $pos+1);
$new_array[$key] = $value;
}
print_r($new_array);
?>
out put of this code is
Array ( [id] => 1 [username] => puneet [mobile] => 0987778987 [u_id] => 232 )
I think you have to split this string two times
divide with space
divide with '='

break array as a string

I have a array:-
Array ( [6] => 1 [6(HL)] => 3 [5] => 1 [7(HL)] => 2 )
How to break it and echo as like this:-
2(6), 3(6(HL)), 1(5), 2(7(HL))
I have try to use implode to break it as a string, but this is what result I get:-
2, 3, 1, 2
any idea on this?
Thanks for advance.
assume your array is $arr :
$output = '';
foreach($arr as $k => $v) {
$output .= $v . '(' . $k . ')' . ', ';
}
$output = substr($output, 0, strlen($output)-2);
echo $output;
$s = implode(', ', array_map(function($a, $b) {
return "$b($a)";
}, array_keys($a), array_values($a)));
Or
$s = '';
foreach ($a as $key => $val)
{
if ($s) $s .= ', ';
$s .= "$val($key)";
}

Categories